JSLint Messages – Use the object literal notation {}

This message is displayed when JSLint encounters an object that has been constructed using new Object() instead of simply = {}.

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.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

4 thoughts on “JSLint Messages – Use the object literal notation {}

  1. Doug Crockford discourages the use of new operator. I think this is in his talk “JavaScript: The Good Parts” and his book.

    Watch his Google tech talk @ youtube:

  2. Pingback: JSLint Messages – Empty Block | James Wiseman

  3. Pingback: JSLint – A Guide To JSLint Messages | James Wiseman

Leave a Reply