Home > Uncategorized > JavaScript Array Literals in IE

JavaScript Array Literals in IE

Just stumbled across wtfjs.com, and would like to submit this classic, specific to IE.

This must be an oldie but always astonishes me when I trip over it. In your browser, try:

var ar = [
           "cat",
           "dog",
           "fish",
        ];

alert(ar.length);

In most browsers it displays 3. In IE8 it displays 4. It’s the trailing comma in the array literal. I think ECMAScript says this is a syntax error, but IE’s behaviour here is extraordinary nonetheless.

Advertisements
Categories: Uncategorized Tags: ,
  1. April 18, 2010 at 12:56 pm

    Correct me if I’m wrong, but I remember that MSIE5 (and 6?) used to choke on that code, saying it was a syntax error. Of course, that would abort all the javascript in that code-scope.

    What joy now, then, that it merely appends a fake item 🙂

  2. April 30, 2010 at 9:46 am

    dang fun story man.

  3. Alex Meiburg
    November 20, 2011 at 12:39 am

    considering that [0,false,””,null,undefined,undefined].length==6, this isn’t all that bad. I assume IE is simply interpreting (incorrect) code differently and appending a null to the end. Not that bad really.

    • earwicker
      January 16, 2012 at 9:54 am

      No, it’s astonishingly terrible. All other languages that derive their syntax from C will ignore trailing commas in such initializers. This is so you can maintain the contents of the list easily: add items, remove, re-order. JavaScript made the original mistake of specifying that trailing commas are a syntax error. But it turned out to be not so bad because all the browser implementations ignore the trailing comma (the only sensible action given any familiarity with the lessons learned from all other C-syntax languages). All browsers, that is, apart from IE! Earlier versions of IE actually reported the syntax error, which isn’t so bad because at least it makes the problem obvious. More recent versions don’t report it and just take the insane step of adding an undefined value to the end of the array, which is quite possibly the worst choice they could have made, from every perspective.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: