Skip to main content

Command Palette

Search for a command to run...

Different ways to create an object.

Updated
2 min read
S

Softwares are art and I am an artist

There are many ways to create an object in javascript as below:

  1. Object Constructor

The simplest ways to create an empty object using the object constructor.

var object = new Object();

Note: Currently, this method is not recommended.

  1. Object Create method

The create method of ‘Object’, creates a new object as a parameter.

var object = Object.create(null);
  1. Object literal method

The object literal syntax is equivalent to create method when it passes null as parameter.

var object = {};
  1. Function Constructor

Create any function and apply the new operator to create a new object instance.

function Person(name){
    var object = {};
    object.name = name;
    object.age = 22;
    return object;
}

var object = new Person("Sagar");
  1. Function Constructor with prototype:

This is similar to function constructor but it uses prototype for their properties and methods,

function Person(){};
Person.prototype.name = "Sagar";
var object = new Person();

This is equivalent to an instance created with an object create method with a function prototype and then call that function prototype and then call that function with an instance & parameters as argument.

function func{}
new func(x,y, z);

OR

function func{}

// create a new instance using function prototype
var newInstance = Object.create(func.prototype)

// Call the function
var result = func.call(newInstance,x,y,z);

// If the result is a non-null object then use it otherwise just use the new instance
console.log(result && typeof result === "object"? result : new Instance)
  1. ES6 Class Syntax

ES6 introduces class feature to create the object.

class Person{
    constructor(name){
        this.name = name;
    }
}

var object = new Person("Sagar")
  1. Singleton Pattern:

A Singleton is an object which can only be instantiated one time reapeated calls to its constructor return the same instance and this way one can ensure that they don’t accidentally create multiple instances.

var object = new function (){
    this.name = "Sagar";
}
36 views

Cracking JS interviews

Part 1 of 5

Master JavaScript interviews with this in-depth series covering core concepts, tricky questions, coding patterns, and system design — all tailored to help you ace your next tech interview with confidence.

Up next

Prototype chaining

Prototype chaining in JavaScript is a mechanism used to implement inheritance by linking objects through their prototypes. If a property or method is not found on an object, the JavaScript engine looks up the chain via the object's [[Prototype]] (acc...