Subtle Difference Between JavaScript Evaluation in IE vs. Firefox…

I came across an annoying difference between the way IE and Firefox interpret JavaScript array lengths. Consider the following snippet:


var a1 = [1,2,3,4];
var a2 = [1,2,3,4,];

alert("a1.length = [" + a1.length + "], a2.length = [" + a2.length + "]");

So basically the only difference between a1 and a2 is that a2 has a trailing comma at the end of the array initializer (legal in both Java and JavaScript). Anyway, in Firefox, the lengths of these two arrays are the same (as I would expect), the alert evaluates to :

a1.length = [4], a2.length = [4]

In IE, however, the lengths are different (it actually increases the size of the array for the trailing comma – <sigh>)

a1.length = [4], a2.length = [5]

Grrrrr…

Advertisements

3 Responses to Subtle Difference Between JavaScript Evaluation in IE vs. Firefox…

  1. Owen Fellows says:

    I personally think IE has it correct as you have declared an array with 5 elements (of which one is empty) so the size of the array should be 5. If you did the same in any other statically typed language using null you would not expect the array to be “trimmed” for you. This does not hold for javascript, of course, as you can dynamically add elements to an array.

    Just my opinion.

  2. lhankins says:

    Incidentally – Java also supports the “trailing comma” syntax when populating an array (it has the same behavior as JS in Firefox though – the trailing comma doesn’t mean you get an extra element in the array).

    I often use the trailing comma syntax this if I’m putting each item in an array literal its own new line, since that makes it very easy to add items later on (otherwise, I tend to forget to go back and add the comma between the next to last entry and the last entry). For example :

    String[] fruits = new String[] {
    "apples",
    "oranges",
    "pears",
    "bananas",
    }

    Now, to add “grapes” at the end of this array, you just copy the last element (“bananas”) and change the String value (you don’t have to remember to go back and add an extra comma after “bananas” – as its already there).

  3. Owen Fellows says:

    I didn’t realise this as I don’t use Array’s that much in Java but I am suprised that the “fifth element” is not populated as a null string.

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: