2013-07-14

Trailing commas in object literals and array literals

Quick reminder: trailing commas in object literals are legal in ECMAScript 5, trailing commas in arrays are ignored.

Trailing commas in object literals

Thus, if you can afford to ignore older JavaScript engines, you can write your object literals like this:
    var obj = {
        first: 'Jane',
        last: 'Doe',
        age: 40,  // trailing comma
    };
The advantage of adding a trailing comma is that you can rearrange the innards of the literal without having to worry about commas being in the right places.

Trailing commas in array literals

Similarly, trailing commas in arrays are ignored:
    > var arr = [ 'a', 'b', 'c', ];
    > arr
    [ 'a', 'b', 'c' ]
    > arr.length
    3
This goes so far that you need to write two trailing commas if you want to add a trailing hole [1]:
    > var arr = [ 'a', 'b', , ];
    > arr.length
    3

Trailing commas in JSON

JSON [2] is based on JavaScript’s syntax prior to ECMAScript 5, which means that trailing commas are illegal:
    > JSON.parse('{"x":1,}')
    SyntaxError: Unexpected token }
    > JSON.parse('[1,]')
    SyntaxError: Unexpected token ]

What browsers support object literals with trailing commas?

Most browsers support object literals with trailing commas. You are only out of luck in Internet Explorer 8 and earlier (compatibility table).

References

  1. Arrays in JavaScript
  2. JavaScript’s JSON API

No comments: