Entries tagged [google-closure]

IE 8 and trailing commas in JavaScript

Feb 27, 2015


How many elements does this JavaScript array object have? (note the comma at the end after which there is no element):

var an_array = [1, 2, 3, ]

This is what the ECMASript Language Specification says about commas in array initialisers:

Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.

So the answer to our question would be 3 as the trailing comma would be ignored. You can confirm this by bringing up the console in developer tools in Firefox or Chrome entering the array definition and printing out its length:

> var an_array = [1, 2, 3, ]
            
> an_array.length

< 3

Read more...