Different ways to create an Object in Javascript.

Different ways to create an Object in Javascript.

Creating objects made easy

Let us start with common ones.

Object Constructor :

let obj = new Object();

This creates an empty object, here it is obj.

Object Literal Syntax :

let obj = {}

This is just assigning an empty object to variable obj.

Object's create Method:

let obj = Object.create(null); // also instead of null, we can pass empty obeject {}.

The create method on Object creates a new object, when passed prototype object as parameter. This is a longer way of Object Literal Syntax.

ES6 Class Syntax:

class Animal{
    constructor(species){
        this.species = species
    }
}
let Animal_1 = new Animal("Dog") // { species:"Dog" }

When created a new instance of Animal, the constructor function is called and thereby creating an object. This is ES6 way of creating objects using classes. The same result can be obtained Function Constructor, which is now an old way to do it.

Singleton Pattern:

let obj = new function(){
    this.name = "Whatever"
}

This method will be more useful when we do not want to create multiple instances, as the name Singleton suggests, object can only be instantiated one time. Even though it is called repeatedly, it returns the same instance.

And many more...

Still, there are many ways to create objects but we have seen the most common methods. When to use what?

  1. Do you want to create several similar objects? Then go for ES6 Class Syntax
  2. Do you need only one object of a kind? Then go for Singleton Pattern
  3. If your object's properties depend on some other objects or if you have Dynamic property names and values Then go for Object Literal Syntax or Object create Method.
  4. According to the current ES6 trend, Object Constructor method is not recommended.

Now What!?

Try to find out why Object Constructor method is not recommended and How to create objects using the Function Constructor Prototype. Comment down below what you found!

Peace 🤞