Black lives matter
Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “JavaScript for impatient programmers”
Book, exercises, quizzes
(free to read online)
Cover of book “Deep JavaScript”
Book (50% free online)
Cover of book “Tackling TypeScript”
Book (first part free online)
Logo of newsletter “ news”
Newsletter (free)

Trailing commas in object literals and array literals

[2013-07-14] dev, javascript, jslang
(Ad, please don’t block)

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
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

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).


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