myArray.length in ECMAScript 262
The number of items in the array.
- Property Type
- Number
This property returns an integer value that is one greater than the largest index in the array. As arrays are sparse, it is mostly a convenience property for iterating over the specified values in an array. Consider the following code:
var foo = [];
// ** foo.length is 0
// ** foo[10] is undefined -- typeof(foo[10])=='undefined'
foo[0]='Hello';
foo[1]='World';
// ** foo.length is now 2
foo.length=10;
foo[6] = "Zebras";
// ** foo.length is now 10
// ** foo[5] is undefined, despite being 'in' the array
foo.length=0;
// ** foo[0] is now undefined, having previously been "Hello"
In the above, we see that:
- If not previously set, the value of any element in an array is
undefined
, whether no matter how big or small thelength
of the array is. (Setting the array to a specific size does not prefill the intermediate indexes with any particular value, includingnull
.) - Assigning a value to an index greater than the current
length
is legal, and autogrows the array. - Setting the length to a new value is legal. Setting the
length
to a value smaller than it was previously causes all indexes of greater value to be cleared (set toundefined
).
Note that it is almost always (slightly) faster to assign the number of items in an array to a local variable when iterating the array, rather than looking up the length
on each iteration:
for (var i=0,len=myArray.length;i<len;i++){ ... }