Over a million developers have joined DZone.
Silver Partner

Quick JavaScript tip: trailing commas inside an object literal

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with JetBrains. Produce high quality code with no additional effort, thanks to state-of-the-art code analysis, on-the-fly error prevention with PhpStorm.

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

The Web Dev Zone is brought to you in partnership with JetBrains. Streamline your workflow by integrating with everything you need for productive development with WebStorm.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}