6 Ways to create a javascript object

Last Updated On

Table of contents

Object literal notation

This is the most common and popular way of creating an object and used to save data in a structured way. Always refers to the prototype of the main Object.

The "new()" keyword

This approach produces the same outcome as a previous mechanism (refers to main Object's prototype) but has different syntax. Less popular since requires more typing :-)

The Object.create(...) method

Unlike the first two examples, the purpose of create method is to create a new object with specific prototype. In the first two cases the prototype of the main object was used, but in this case, we should pass an object into create() which will be considered as a prototype.

In this example, anotherPizza will not have all default methods and fields that come from the default main Object. It will only have methods and fields that came from pizza object as it was passed as an anotherPizza's prototype.

Constructor function

By using this approach we created a new object which also has its own prototype. However, compared to point 3, in the current example pizza will have fields and methods from Pizza plus all methods and fields from the main Object since Pizza's prototype' was inherited from the mainObject's prototype.

This way is useful when it's necessary to create multiple objects with the same base functionality.

The object.assign(...) method

Even though syntactically it's completely right, using assign() it this way is not common.

However, it's extremely helpful when it's necessary to create a new object with a new reference in memory based on the existing one:

In addition to that, Object.assign() produces a new object in an immutable way (doesn't modify the old one in a case it will be changed).

Sidenote: If it's not clear why doing

is a bad idea, you need to read more about reference types (in javascript all objects are reference types).

The JSON.parse(JSON.stringify(object)) method

Even though it sounds like a hack, this method is very popular and useful when dealing with copying/cloning objects with deep structure. The same as the previous example, it does create a completely new object in an immutable way.

The reason it exists is that it's the only one method available out of the box that can do deep clone/copy. As a sidetone object.assign is not good at it.