top of page

Objects in JavaScript

Objects in JavaScript (and other programming languages) is basically a collection of properties which is an association between a name and a value, similar to how variables work.

​

Objects in JavaScript is like objects in the real world. The screen (mobile, monitor etc.) you are looking at now is an object. It has a size (height and width) and a frame with a color. Just like the screen, objects in JavaScript can have properties.

​

Programming is often used to solve real world problems and uses objects to describe real world objects. So this makes it easy to link an object in JavaScript to an real object.

​

In JavaScript objects can be created in multiple different ways. Here we will show you how.

​

Object initializers:

The properties names goes before the colons and the values goes after the colons.

​

The object is now created and is assigned to the variable someObject. This way of creating objects is great if you need to create just one or just a few.

 

Sometimes you need many objects or many objects of a specific type but with different values. In these cases using a constructor function to create objects. Using a constructor function is like making a blueprint where everything is defined and you can use it to build the actual object.

 

Constructor function: 

The function takes values in through the parameters and assign the values to the properties on the object using this.

​

Now we can easily create multiple cars if we want to. We create a new instance of the object with the keyword new.

See how easy it was to create two instances!

The last method is the Object.create() method. With object.create() we don't need to define a constructor, so this way of creating objects is very handy.

​

Object.create()

Nice! Now we know how to create objects so it's time to look at how we can access properties to show or modify them.

​

We can access properties in two ways, either with dot notation or bracket notation. Let's have a look. 

So now you know how to create objects and how to access their properties. After ES6 this is not the only way of dealing with objects in JavaScript. As other object-oriented languages JavaScript has Classes which helps when creating hierarchies and dealing with inheritance. We will look at classes in JavaScript in the next page.

©2022 - 2024 by JavaScript Schools.

bottom of page