Hoping someone can shed some light on this simple piece of code not working as expected:
var arr = new Array(10);
arr.length; // 10. Why? Very wierd.
Why does it return 10?
It returns 10, because you give only one integer, as argument, to the Array constructor. In this case, the new Array constructor is acting like some programming languages where you needed to specify the memory for your array so you don't get those ArrayIndexOutOfBounds Exceptions. An example of this in Java:
int[] a = new int[10];
Or C#:
int[] array = new int[5];
In Javascript, when you write:
var a = new Array(10);
a[0] // returns undefined
a.length // returns 10.
and if you write:
a.toString() // returns ",,,,,,,,,", a comma for each element + 1
But, since Javascript doesn't need to allocate memory for an array, is better to use use the [] constructor:
var a = [10];
a[0] //returns 10
a.length //returns 1
I think that the thing that confuse all the people is this:
var a = new Array(1,2,3,4,5);
a[0] // returns 1
a.length // returns 5
But you can do the same in this way:
var a = [1,2,3,4,5];
a[0] // returns 1
a.length // returns 5
So, in conclusion, try to avoid using the new Array constructor, and use the [] constructor instead.