Posts Tagged: length


22
Oct 08

Inconsistencies with array length in Javascript

What you’d say is the size of [1,2,] in Javascript?
Until last day I’d say 2 without much thinking. But under IE, the size is 3, because of the last comma.
Now, it’s valid to define arrays like this [,,1], [1,,2] or even [1,,]. All of them having 3 elements. But what about this particular case when having a single comma after the last element?.

The definition of the correct behaviour is stated in ECMA-262, section 11.1.4 Array Initialiser, which I didn’t bother to read as I’ve already made my mind and decided this is another IE bug.

The reasons for thinking this is a bug are:

  • It’s simpler to generate js code from another language without the need to check if it’s the last element or not and add a comma when needed.
  • When leaving a comma after the last element in another languages, for example Ruby, Python or Java, that last comma does not add another ‘undefined’ element to the array (ok, I don’t know how much valid is to compare other languages to js in this aspect, but I like this feature).

Tested on: IE 7, Firefox 3 (linux/win)