[javascript] What is the difference between `new Object()` and object literal notation?

What is the difference between this constructor-based syntax for creating an object:

person = new Object()

...and this literal syntax:

person = {
    property1 : "Hello"
};

It appears that both do the same thing, although JSLint prefers you use object literal notation.

Which one is better and why?

This question is related to javascript object jslint

The answer is


Actually, there are several ways to create objects in JavaScript. When you just want to create an object there's no benefit of creating "constructor-based" objects using "new" operator. It's same as creating an object using "object literal" syntax. But "constructor-based" objects created with "new" operator comes to incredible use when you are thinking about "prototypal inheritance". You cannot maintain inheritance chain with objects created with literal syntax. But you can create a constructor function, attach properties and methods to its prototype. Then if you assign this constructor function to any variable using "new" operator, it will return an object which will have access to all of the methods and properties attached with the prototype of that constructor function.

Here is an example of creating an object using constructor function (see code explanation at the bottom):

function Person(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
}

Person.prototype.fullname = function() {
    console.log(this.firstname + ' ' + this.lastname);
}

var zubaer = new Person('Zubaer', 'Ahammed');
var john = new Person('John', 'Doe');

zubaer.fullname();
john.fullname();

Now, you can create as many objects as you want by instantiating Person construction function and all of them will inherit fullname() from it.

Note: "this" keyword will refer to an empty object within a constructor function and whenever you create a new object from Person using "new" operator it will automatically return an object containing all of the properties and methods attached with the "this" keyword. And these object will for sure inherit the methods and properties attached with the prototype of the Person constructor function (which is the main advantage of this approach).

By the way, if you wanted to obtain the same functionality with "object literal" syntax, you would have to create fullname() on all of the objects like below:

var zubaer = {
    firstname: 'Zubaer',
    lastname: 'Ahammed',
    fullname: function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
};

var john= {
    firstname: 'John',
    lastname: 'Doe',
    fullname: function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
};

zubaer.fullname();
john.fullname();

At last, if you now ask why should I use constructor function approach instead of object literal approach:

*** Prototypal inheritance allows a simple chain of inheritance which can be immensely useful and powerful.

*** It saves memory by inheriting common methods and properties defined in constructor functions prototype. Otherwise, you would have to copy them over and over again in all of the objects.

I hope this makes sense.


The only time i will use the 'new' keyowrd for object initialization is in inline arrow function:

() => new Object({ key: value})

since the below code is not valid:

() => { key: value} //  instead of () => { return { key: value};}

Memory usage is different if you create 10 thousand instances. new Object() will only keep only one copy while {} will keep 10 thousand copies.


Also, according to some of the O'Really javascript books....(quoted)

Another reason for using literals as opposed to the Object constructor is that there is no scope resolution. Because it’s possible that you have created a local constructor with the same name, the interpreter needs to look up the scope chain from the place you are calling Object() all the way up until it finds the global Object constructor.


In JavaScript, we can declare a new empty object in two ways:

var obj1 = new Object();  
var obj2 = {};  

I have found nothing to suggest that there is any significant difference these two with regard to how they operate behind the scenes (please correct me if i am wrong – I would love to know). However, the second method (using the object literal notation) offers a few advantages.

  1. It is shorter (10 characters to be precise)
  2. It is easier, and more structured to create objects on the fly
  3. It doesn’t matter if some buffoon has inadvertently overridden Object

Consider a new object that contains the members Name and TelNo. Using the new Object() convention, we can create it like this:

var obj1 = new Object();  
obj1.Name = "A Person";  
obj1.TelNo = "12345"; 

The Expando Properties feature of JavaScript allows us to create new members this way on the fly, and we achieve what were intending. However, this way isn’t very structured or encapsulated. What if we wanted to specify the members upon creation, without having to rely on expando properties and assignment post-creation?

This is where the object literal notation can help:

var obj1 = {Name:"A Person",TelNo="12345"};  

Here we have achieved the same effect in one line of code and significantly fewer characters.

A further discussion the object construction methods above can be found at: JavaScript and Object Oriented Programming (OOP).

And finally, what of the idiot who overrode Object? Did you think it wasn’t possible? Well, this JSFiddle proves otherwise. Using the object literal notation prevents us from falling foul of this buffoonery.

(From http://www.jameswiseman.com/blog/2011/01/19/jslint-messages-use-the-object-literal-notation/)


On my machine using Node.js, I ran the following:

console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');

console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');

console.log('Testing Object:');

console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');

console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');

Note, this is an extension of what is found here: Why is arr = [] faster than arr = new Array?

my output was the following:

Testing Array:
using[]: 1091ms
using new: 2286ms
Testing Object:
using{}: 870ms
using new: 5637ms

so clearly {} and [] are faster than using new for creating empty objects/arrays.


I have found one difference, for ES6/ES2015. You cannot return an object using the shorthand arrow function syntax, unless you surround the object with new Object().

> [1, 2, 3].map(v => {n: v});
[ undefined, undefined, undefined ]
> [1, 2, 3].map(v => new Object({n: v}));
[ { n: 1 }, { n: 2 }, { n: 3 } ]

This is because the compiler is confused by the {} brackets and thinks n: i is a label: statement construct; the semicolon is optional so it doesn't complain about it.

If you add another property to the object it will finally throw an error.

$ node -e "[1, 2, 3].map(v => {n: v, m: v+1});"
[1, 2, 3].map(v => {n: v, m: v+1});
                           ^

SyntaxError: Unexpected token :

2019 Update

I ran the same code as @rjloura on my OSX High Sierra 10.13.6 node version 10.13.0 and these are the results

console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');

console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');

console.log('Testing Object:');

console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');

console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');


Testing Array:
using[]: 117.613ms
using new: 117.168ms
Testing Object:
using{}: 117.205ms
using new: 118.644ms

Everyone here is talking about the similarities of the two. I am gonna point out the differences.

  1. Using new Object() allows you to pass another object. The obvious outcome is that the newly created object will be set to the same reference. Here is a sample code:

    var obj1 = new Object();
    obj1.a = 1;
    var obj2 = new Object(obj1);
    obj2.a // 1
    
  2. The usage is not limited to objects as in OOP objects. Other types could be passed to it too. The function will set the type accordingly. For example if we pass integer 1 to it, an object of type number will be created for us.

    var obj = new Object(1);
    typeof obj // "number"
    
  3. The object created using the above method (new Object(1)) would be converted to object type if a property is added to it.

    var obj = new Object(1);
    typeof obj // "number"
    obj.a = 2;
    typeof obj // "object"
    
  4. If the object is a copy of a child class of object, we could add the property without the type conversion.

    var obj = new Object("foo");
    typeof obj // "object"
    obj === "foo" // true
    obj.a = 1;
    obj === "foo" // true
    obj.a // 1
    var str = "foo";
    str.a = 1;
    str.a // undefined
    

There is no difference for a simple object without methods as in your example. However, there is a big difference when you start adding methods to your object.

Literal way:

function Obj( prop ) { 
    return { 
        p : prop, 
        sayHello : function(){ alert(this.p); }, 
    }; 
} 

Prototype way:

function Obj( prop ) { 
    this.p = prop; 
} 
Obj.prototype.sayHello = function(){alert(this.p);}; 

Both ways allow creation of instances of Obj like this:

var foo = new Obj( "hello" ); 

However, with the literal way, you carry a copy of the sayHello method within each instance of your objects. Whereas, with the prototype way, the method is defined in the object prototype and shared between all object instances. If you have a lot of objects or a lot of methods, the literal way can lead to quite big memory waste.


There are a lot of great answers here, but I want to come with my 50 cents.

What all of these answers are missing is a simple analogy which would work for a person who just starts his journey in the programming languages.

Hopefully, I will fill this gap with this analogy:

Object Literal Creation vs Constructor-based Syntax

Feel the difference with a sentence creation.

If I have a sentence "I like cheese", I can tell you clearly and loudly (literally, or verbatim): I like cheese.

This is my literal (word by word) creation of the sentence.

All other ways are some tricky ways of making you to understand of what sentence I created exactly. For example, I tell you:

  1. In my sentence, the subject is "I", the object is "cheese", and the predicate is "to like". This is another way of YOU to learn without any ambiguities the very same sentence: "I like cheese".

Or,

  1. My sentence has 3 words: the first one is the n-th word in the English dictionary, the the second one is the m-th word in the English dictionary and the last one is the l-th word in the English dictionary.

In this case, you also come to the same result: you know exactly what the sentence is.

You can devise any other methods which would differ from "word-by-word" sentence creation (LITERAL), and which would be INDIRECT (non literal, non verbatim) method of sentence creation.

I think this is the core concept which lays here.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to jslint

Why does JSHint throw a warning if I am using const? JSLint says "missing radix parameter" Should I use JSLint or JSHint JavaScript validation? How to initialize an array's length in JavaScript? What is the difference between `new Object()` and object literal notation? JSLint is suddenly reporting: Use the function form of "use strict" What does the JSLint error 'body of a for in should be wrapped in an if statement' mean? What does "use strict" do in JavaScript, and what is the reasoning behind it? Why avoid increment ("++") and decrement ("--") operators in JavaScript?