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?
They both do the same thing (unless someone’s done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It’s clearly recognizable as to what is happening, so using
new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.These
technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.
The “something unusual” that someone could do would be to shadow or assign to the default
Objectglobal:In that highly-unusual case,
new Objectwill fail but{}will work.In practice, there’s never a reason to use
new Objectrather than{}(unless you’ve done that very unusual thing).