Please enable JavaScript to use CodeHS

Basic Objects in JavaScript

In this tutorial, we'll take a look at the basics of creating an object with properties and methods in JavaScript.

By Ryan Hart

What Is An Object?

In JavaScript, an object is a data structure that can hold a wide variety of information all in one place. It’s kind of like an array in that sense, but the information in an object is unordered and much more easily accessible. This is because the data in an object is stored in a series of key-value pairs, kind of like a contact list in your phone – if you want to access a number (value), you need to find the appropriate name (key).

Object Properties

If you think about it, all information can be organized in key-value pairs. Take a look at the image below of two car objects – they are individual entities with unique information or properties, stored in key-value pairs.


In programming, we call key-value pairs like these the properties of an object. For example, saying “the car’s color property is white” is the same thing as saying, “the value associated with the car’s color key is white.” Properties describe the state of an object – the current condition of the object at a given moment in time.

One of the powerful aspects of storing information in an object is that if you want to know a value of a property, like the color of the car object, you don’t need to know where that information is kept, like you would with an array, but just what the property is called – “color”!

Our First Object

Creating the Object

Let’s now create a car object in JavaScript. There are a few ways to do this, but the most basic way is to create an object literal, which is simply a variable, car1, initialized with curly brackets:

let car1 = {};
JavaScript

This creates an empty object, which isn’t all that interesting. Let’s create it again, but this time include the key-value properties:

let car1 = {make:"tesla", model:"3", color:"white", year:2020};
JavaScript

Notice that the keys and values of the properties are separated by a colon, and that there is a comma in between each pair. This same code is often written in the format below, which is easier to read:

let car1 = {
    make: "tesla",
    model: "3",
    color: "white",
    year: 2020
};
JavaScript

Note: The key names do not need quotation marks around them unless it is two words, like “wheel size”.


Accessing Property Values

In order to access these property values, there are two techniques you can use: dot notation and bracket notation. Dot notation is more commonly used because it’s quicker to write and easier to read, but if a key name is two words, or is stored in a variable, then you have to use bracket notation.

  • dot notation – you write the object’s variable name, then a dot, then the property name.

    console.log(car1.make);        \\ prints "tesla"
    JavaScript
  • bracket notation – you write the object’s variable name and the property name within square brackets, surrounded by quotes.

    console.log(car1["make"]);        \\ prints "tesla"
    JavaScript


Creating New Property Values

You can also use both notations to create new properties, or assign new values. For example, the code below uses both notations to create two new properties:

car1.doors = 4;
car1["weight"] = 4000;
JavaScript

If the property already exists, then the same code assigns a new value to the established key:

car1.model = "S";
car1["year"] = 2022;
JavaScript

Take a look at all of this in action in the editor below. Try adding your own property to the objects and printing out its value!

Object Methods

If properties describe the state of an object, like “the car is white”, then methods describe its behavior. They are what an object can do (behavior), as opposed to what the object currently is (state). Methods are the actions associated with an object.

Likely you’ve already come across something very similar in your programming experience – functions! When you define a function, you are defining an action that will be executed when called. Methods are just the functions of objects. When you call an object’s method, something happens!

Let’s create an animal object that has the properties of name and type, and a method called speak.

let animal1 = {
    name: "Eleanor",
    type: "giraffe",
    speak: function() {
        console.log("Hi, my name is " + this.name + ". I'm a " + this.type + ".");
    }
}
JavaScript

A couple of things to notice about the speak method:

  • It’s just another type of key-value pair, where the key is “speak” and the value is a function to be executed. Instead of a property, it’s a method!

  • Dot notation is used to access the properties of the object, name and type. The only difference here is that the keyword this is used instead of animal1 because the function is inside of the object. The this keyword, when used inside of an object, refers to the object itself.

To call this method, you use the dot notation (like you would in accessing the properties), but add open/close parentheses at the end. This is just like you are calling a normal function!

animal1.speak();        // prints "Hi, my name is Eleanor. I'm a giraffe."
JavaScript

Check out the example below in the editor. Can you add your own method and call it?

The “in” Keyword

The in keyword can be helpful when working with objects. Below describes two different scenarios in which it is used.


1. The Existence of a Key

If you want to know if an object has a specific key, you can use the in keyword to set up a Boolean expression: key in object.

For example, let’s say you have an object that stores the names (key) and email addresses (value) of your employees. You want to know if the key “Sarah” already exists so that you don’t accidentally overwrite it with a new value.

let emails = {
    Larry: "larry@codehs.com",
    Sarah: "sarah@codehs.com",
    Hank: "hank@codehs.com"
}

let newName = "Sarah";

if (newName in emails) {
    console.log(newName + " is already in the object.");
} else {
    emails[newName] = newName.toLowerCase() + "@codehs.com";
}
JavaScript

Since “Sarah” does already exist as a key, “Sarah is already in the object.” will print to the console.


2. Iterating Through an Object

The second use of the in keyword is in iterating through all of the keys in an object with a for loop. Extending the example above, let’s say you now want to print out all of the names (keys) and email addresses (values) of your employees.

let emails = {
    Larry: "larry@codehs.com",
    Sarah: "sarah@codehs.com",
    Hank: "hank@codehs.com"
}

for (let name in emails) {
    console.log(name +": " + emails[name]);
}
JavaScript

Notice that the variable name is grabbing each key in the emails object. To access the values (the email addresses), you use bracket notation with it and the object.


In the editor below, we created the addName() function that will add a name to emails only if it doesn’t already exist, and the printNames() function that iterates through the emails object, printing out every key-value pair.

A Graphics Example

Another great use case for objects is with graphics and animations. Each moving object can store its own information (properties) about its size, location, speed, color, etc. This eliminates the need to have multiple variables to keep track of them.

In the example below, there are three balls bouncing around the canvas. Take note of the properties and values of each. The last property is the circle graphic for each ball, which actually is an object itself! We have put the ball objects in an array so that we can access each object and move them efficiently. Imagine how many more variables we would need if we had to store each of the three ball’s properties separately.

Try changing the values of the initial properties and see how it affects the animation.


Be sure to check out our Advanced Objects tutorials to learn about object constructors in part 1 and object prototypes and inheritance in part 2!