Creating empty object in JavaScript…

Photo by Mazhar Zandsalimi on Unsplash

Every time you create an object in JavaScript either with the object literal ({}) or using “new Object()” behind the scene JavaScript invokes the constructor function of Object to create the object.

It always allows your new object to inherit some properties using the inheritance Object.prototype. Consider the following:

Object with inherited properties

But sometimes we need to create an object that doesn’t inherit any properties from the prototype. For instance, If you’d like to use an object as a hash/map of arbitrary keys to values. So, how we are going to do that:

Fortunately, Object.create() make that easy.
Object with no inherited properties

As you can see there are no inherited properties in emptyObj. There is not only one property name that we explicitly set at the time of creating an object.

The trick is here is the first parameter of the Object.create() function where we pass the object that we need as a prototype to new object, but If we pass null instead then new object doesn’t inherit from prototype at all.

Here is the browser compatibility of Object.create() method.

Browser compatibility of Object.create() method

That’s it, I hope you find it helpful.

Clap & Follow.

Comments