Objects in JavaScript (With Examples)

Richard Rembert - Sep 13 '22 - - Dev Community

Objects in JavaScript are used to store collections of data in the format of “key: value” pairs. Contained within an object we can have any number of variables and/or functions which are then referred to as object properties and methods.

Creating an Object

Let’s work with an example! To initialize a variable car as an object*,* we use curly braces {}:

var car = {};
Enter fullscreen mode Exit fullscreen mode

We now have an empty object which can be accessed via the Developer Tools console, by simply typing our variable name:

car

// {} [object]
Enter fullscreen mode Exit fullscreen mode

An empty object isn’t all that useful, so let's update it with some data:

var car = {
  name: 'Tesla',
  model: 'Model 3',
  weight: 1700,
  extras: ['heated seats', 'wood decor', 'tinted glass'],
  details: function() {
    alert('This ' + this.name + ' is a ' + this.model + ' it weighs ' + this.weight + 'kg and includes the following extras: ' + this.extras[0] + ', ' + this.extras[1] + ' and ' + this.extras[2] + '.');
  },
  display: function() {
    alert('This car is a ' + this.name + '.');
  }
};
Enter fullscreen mode Exit fullscreen mode

Let’s access this data in our developer tools console:

car.name         // Tesla
car.model        // Model 3
car.weight       // 1700
car.extras[1]    // wood decor
car.details()    // This Tesla is a Model 3 it weighs 1700kg and   includes the following extras: heated seats, wood decor and tinted glass.
car.display()    // This car is a Tesla.
Enter fullscreen mode Exit fullscreen mode

As you can see, each name/value pair must be separated by a comma, and the name and value in each case are separated by a colon. The syntax will always follow this pattern:

var objectName = {
  member1Name: member1Value,
  member2Name: member2Value,
  member3Name: member3Value
};
Enter fullscreen mode Exit fullscreen mode

The value of an object member can be pretty much anything — in our car object, we have two strings, a number, an array, and two functions. The first four items are data items and are referred to as the object’s properties. The last two items are functions that allow the object to do something with that data and are referred to as the object’s methods.

This kind of object is called an object literal — we’ve literally written out the object contents as we’ve created it. This is in comparison to objects instantiated from classes, which we’ll take a look at later on.

Dot Notation

Above, you’ve seen the object’s properties and methods accessed using dot notation. The object name car acts as the namespace — it needs to be entered first to access anything within the object. Then you write a dot, followed by the item you want to access — this can be the name of a simple property, an item of an array property, or a call to one of the object’s methods, for example:

car.name
car.extras[1]
car.details()
Enter fullscreen mode Exit fullscreen mode

Deleting Properties

We can use the delete operator to remove properties, like so:

car.model
// Tesla 3

delete car.model

car.model
// undefined
Enter fullscreen mode Exit fullscreen mode

Square Brackets

If for example, we had a multi-word property within our object, such as:

var user = {
  name: "Richard",
  age: 32,
  "likes steaks": true  // a multiword property name must be quoted
};
Enter fullscreen mode Exit fullscreen mode

We couldn’t access the multi-word property with dot-notation:

user.likes potatoes     // syntax error!
Enter fullscreen mode Exit fullscreen mode

This is because a dot requires the key to be a valid variable identifier. That is no spaces and other limitations.

The alternative is to use square brackets, which works with any string:

let user = {};

// set
user["likes steaks"] = true;

// get
alert(user["likes steaks"]); // true

// delete
delete user["likes steaks"];
Enter fullscreen mode Exit fullscreen mode

Updating Object Members

We can update the values within our objects by simply declaring the property you’d like to set with the new value, like so:

user.age          // 32
user.age = 33     // 33
user.age          // 33
Enter fullscreen mode Exit fullscreen mode

You can also create completely new members of your object. For example:

user.surname = 'Smithessson';
// user
{name: "Richard", age: 33, likes steaks: true, surname: "Rembert"}
Enter fullscreen mode Exit fullscreen mode

What is “this”?

You may have noticed the use of the word ‘this’ in our earlier example. See the following:

display: function() {
  alert('This car is a ' + this.name + '.');
}
Enter fullscreen mode Exit fullscreen mode

The this keyword refers to the current object that the code is being written inside of— so in this case this is equivalent to car.

Why not just write car instead? It’s best practice to write well-constructed object-orientated code, and in doing so the use of this is extremely useful. It will ensure the correct values are used when a member's context changes (e.g. two different car object instances may have different names, but will want to use their own name when displaying their own information).

For example:

var car1 = {
  name: 'Tesla',
  display: function() {
    alert('This car is a ' + this.name + '.');
  }
}
var car2 = {
  name: 'Toyota',
  display: function() {
    alert('This car is a ' + this.name + '.');
  }
}
Enter fullscreen mode Exit fullscreen mode

In this case, car1.display() will output "This car is a Tesla." And car2.display() will output "This car is a Toyota.", even though the method's code is exactly the same in both cases.

As this is equal to the object the code is inside —this becomes really useful when you are dynamically generating objects (for example using constructors), which is outside the scope of this article!

Summary

And that’s it! You should now have a good idea of how to work with objects in JavaScript — including creating your own simple objects, as well as accessing and manipulating object properties. You‘ll also begin to see how objects are very useful as structures for storing related data and functionality.

For instance, if you tried to keep track of all the properties and methods in our car object as separate variables and functions, it would be extremely inefficient, and we'd run the risk of clashing with other variables and functions that have the same names. Objects let us keep the information safely locked away in their own package.

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
Buy Me A Coffee If you enjoyed this article & would like to leave a tip — click here

🌎 Let's Connect

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .