Typically, the length property is determined based on the highest index in the array.
Reading length
1) For a solid array, this means that the length corresponds strictly to the number of elements:
var fruits = ['orange', 'apple', 'banana'];
A dense array has no empty media, and the number of elements corresponds to highestIndex + 1 . In [3, 5, 7, 8] largest index is 3 element 8 , so the size of the array is 3 + 1 = 4 .
2) In the sparse array (which has empty), the number of elements does not match the length value, but is still determined by the highest index
var animals = ['cat', 'dog', , 'monkey']; // animals is sparse animals.length // prints 4, but real number of elements is 3 var words = ['hello']; words[6] = 'welcome'; //the highest index is 6. words is sparse words.length //prints 7, based on highest index
Change length
1) Changing the property leads to cutting out the elements (if the new value is less than the highest index):
var numbers = [1, 3, 5, 7, 8]; numbers.length = 3;
2) or creating a sparse array (if the new value is greater than the highest index):
var osTypes = ['OS X', 'Linux', 'Windows']; osTypes.length = 5; // creating a sparse array. Elements at indexes 3 and 4 // do not exist osTypes // prints ['OS X', 'Linux', 'Windows', , , ]
Please read this post which details the entire length array.