Linked Questions

Popular Questions

Javascript Browser Quirks - array.Length

Asked by At

Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Unusual Array Lengths!</title>

    <script type="text/javascript">
        var arrayList = new Array();
        arrayList = [1, 2, 3, 4, 5, ];
        alert(arrayList.length);
    </script>

</head>
<body>
</body>
</html>

Notice the extra comma in the array declaration. The code above gives different outputs for various browsers:

Safari: 5

Firefox: 5

IE: 6

The extra comma in the array is being ignored by Safari and FF while IE treats it as another object in the array.

On some search, I have found mixed opinions about which answer is correct. Most people say that IE is correct but then Safari is also doing the same thing as Firefox. I haven't tested this on other browsers like Opera but I assume that there are discrepancies.

My questions:

i. Which one of these is correct?

Edit: By general consensus (and ECMAScript guidelines) we assume that IE is again at fault.

ii. Are there any other such Javascript browser quirks that I should be wary of?

Edit: Yes, there are loads of Javascript quirks. www.quirksmode.org is a good resource for the same.

iii. How do I avoid errors such as these?

Edit: Use JSLint to validate your javascript. Or, use some external libraries. Or, sanitize your code.

Thanks to DamienB, JasonBunting, John and Konrad Rudolph for their inputs.

Related Questions