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. http://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.
It seems to me that the Firefox behavior is correct. What is the value of the 6th value in IE (sorry I don’t have it handy to test). Since there is no actual value provided, I imagine it’s filling it with something like ‘null’ which certainly doesn’t seem to be what you intended to have happen when you created the array.
At the end of the day though, it doesn’t really matter which is ‘correct’ since the reality is that either you are targeting only one browser, in which case you can ignore what the others do, or you are targeting multiple browsers in which case your code needs to work on all of them. In this case the obvious solution is to never include the dangling comma in an array initializer.
If you have problems avoiding it (e.g. for some reason you have developed a (bad, imho) habit of including it) and other problems like this, then something like JSLint might help.