Search code examples
javascriptobject-literal

Reliable lengths for a Javascript object array literal?


There are lots of questions like this but...duh...I can't get it to work. How do I...take an object literal like this:

locations = {};

locations.activities = [
{ text:'biking'},
{ text:'hiking'},
{ text:'boating'},
{ text:'studying'},
{ text:'reading'},
];

And print out the activities array values?

IE and Firefox are getting different lengths (6 and 5 respectively).

Thanks


Solution

  • The problem is the trailing comma: remove it for cross-browser compatibility reasons.

    The inconsistent behavior is caused because some browsers parse the literal incorrectly1 when a trailing comma is present. The correct behavior is to ignore the trailing comma2:

    If an element is elided at the end of an array (i.e. [...,]), that element does not contribute to the length of the Array.


    1 The syntax works correctly in IE10 but incorrectly in IE9 and before. This can be verified by testing [1,].length from the console in the relevant browser mode. The values reported are 1 (correct) and 2 (incorrect), respectively.

    2 The trailing comma is relevant in the case of [,] which should be equivalent to [undefined].