HTML5 Zone is brought to you in partnership with:

Dr. Axel Rauschmayer is a freelance software engineer, blogger and educator, located in Munich, Germany. Axel is a DZone MVB and is not an employee of DZone and has posted 246 posts at DZone. You can read more from them at their website. View Full User Profile

Quick JavaScript tip: trailing commas inside an object literal

06.21.2011
| 3425 views |
  • submit to reddit

It used to be that some JavaScript engines weren’t picky about trailing commas inside an object literals, while others threw a syntax error. The ECMAScript 5 language specification [1] has made trailing commas legal, via the following syntax rule (in Sect. 11.1.5):

    ObjectLiteral :
        {}
        { PropertyNameAndValueList }
        { PropertyNameAndValueList , }
You can use this syntax in all modern browsers [3]. It makes it easier to maintain the content inside object literals, especially long ones: You don’t have to keep track which property is last when rearranging things. Take the following example.
    var obj = {
        foo: 123,
        bar: function () { ... },
    }
Thanks to the trailing comma, you save two steps when swapping foo and bar, as there is no need to add a comma after bar or to remove the comma after foo.

Related reading:

  1. Standard ECMA-262: ECMAScript Language Specification
  2. What’s new in ECMAScript 5
  3. ECMAScript 5 compatibility table

 

From http://www.2ality.com/2011/06/object-literal-comma.html

Published at DZone with permission of Axel Rauschmayer, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)