1. Using the Object() constructor:

var d = new Object();

This is the simplest way to create an empty object. I believe it is now discouraged.

2. Using the bracket’s syntactig sugar:

var b = {};

This is equivalent to Object.create(null) method, using a null prototype as an argument.

3. Using a function constructor

var Obj = function(name) {
  this.name = name
}
var c = new Obj("hello"); 

What the new operator does is call a function and setting this of the function to a fresh new Object, and binding the prototype of that new Object to the function’s prototype. As is:

function f {};

new f(a, b, c);

Would be equivalent to: 

// Create a new instance using f's prototype.
var newInstance = Object.create(f.prototype)
var result;

// Call the function
result = f.call(newInstance, a, b, c),

// If the result is a non-null object, use it, otherwise use the new instance.
result && typeof result === 'object' ? result : newInstance

4. Using the function constructor + prototype:

function myObj(){};
myObj.prototype.name = "hello";
var k = new myObj();

5 Using ES6 class syntax:

class myObject  {
  constructor(name) {
    this.name = name;
  }
}
var e = new myObject("hello");

6 Singleton pattern:

var l = new function(){
  this.name = "hello";
}

Thanks for reading!

Originally published by Esteban at coderwall.com

#javascript #web-development

6 Ways to Create an Object in JavaScript
4 Likes38.95 GEEK