17

Possible Duplicate:
creating objects - new object or object literal notation?
Literal notation VS. constructor to create objects in JavaScript

I'm going through my very first Javascript tutorial.

I just found two ways to create a JS object.

var person = new Object();
person.name = "Tom";
person.age = "17";

and

var person = {};
person.name = "Tom";
person.name = "17"

Any difference between these two ways of object creation? Since the second looks simpler, can we always use it under any condition?

Community
  • 1
  • 1
Terry Li
  • 16,870
  • 30
  • 89
  • 134
  • Object literal notation is the preferred way (second in your question). From a performance standpoint, using Chrome 23 on Windows 7 64-bit. Construction function: `198,569,418 Ops/sec`. Object Literal: `200,177,923 Ops/sec`. – Sahat Yalkabov Jan 09 '13 at 00:21
  • Don’t forget `Object.create()` as well. – David Hellsing Jan 09 '13 at 00:23

1 Answers1

28

Not only is the second syntax easier to read and not only will it work under any condition, but the first syntax might not work under all conditions:

function Object() {
    // Oh crap, we have redefined Object!
    return [];    // return an array because we are EVIL
}

var person = new Object();   // not what we think it is

But {}, being a syntactic construct, is immune to such evil trickery.

In addition, the object literal notation can be partially optimized at parse time, since after all there's only one object type that could be created. That may result in a minuscule performance increase.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
  • Shadowing the global `Object`, never thought anyone would think of that. `:P` +1 Nevertheless. – Fabrício Matté Jan 09 '13 at 00:18
  • 3
    Recently I was curious about the performance difference of new vs {} so I tested this on jsperf. The literal was much faster (At least in V8). You can see the results on my blog if you want more info: http://allthingscraig.com/blog/2013/01/02/creating-javascript-objects/ – Craig MacGregor Jan 09 '13 at 00:22
  • That is a rather pointless scenario. If you redefine `Object` your entire script will be broken anyway (also, you won’t be able to create arrays as your example states). – David Hellsing Jan 09 '13 at 00:28
  • It's not at all pointless. People make the same assumptions about `undefined`, to their cost. It is *important* to know what is and is not a keyword in JavaScript. – Platinum Azure Jan 09 '13 at 00:59
  • Sure it’s important to know javascript keywords, but recommending one syntax over another because WHAT IF someone overrides `Object` is not really relevant. Because if someone does that, the syntax wouldn’t matter anyway because your entire script will be broken. – David Hellsing Jan 09 '13 at 09:11
  • 3
    You're not getting it. If someone redefines the Object constructor, you can still use `{}` safely. – Platinum Azure Jan 09 '13 at 14:00