The first two, and the third examples are equivalent, at the end they produce an Array object with only one own property, length, containing 5 as its value.
When you call the Array constructor using a single numeric argument (like Array(5);), the newly created object will contain that number as its length property, the index properties aren't created:
var a = Array(5);
a.hasOwnProperty('0'); // false
The second example produces just the same:
var a = [];
a.length = 5;
a.hasOwnProperty('0'); // false
About the third example, it isn't equivalent because it will create a property on the array object, even though its value is undefined:
var a = []; a[4] = undefined;
a.hasOwnProperty('4'); // true
The fourth example:
var a = new Array(5);
Is just exactly the same as the second one (var a = Array(5);), there's no difference between using the Array constructor with or without the new operator, in the second example you are calling the Array constructor as a function.
And finally, about your makeArrayToLength function, by now I think you know isn't equivalent at all, since all the "index properties" are initialized to a "default" value. (BTW don't use default as Identifier, it's a Keyword...)
The Array constructor is usually avoided because it can have different behaviors depending the argument used, for example:
Array("5"); // one element array, (["5"])
Array(5); // empty array, length = 5
// v.s.
["5"] // one element array
[5] // one element array
Also, the Array
answered 2010-12-09T06:37:14.323