Array Length
Last updated
Was this helpful?
Last updated
Was this helpful?
When the elements in the array are contiguous, then the length property indicates the number of elements in the array and the array is considered to be a dense array. This is true when there are no empty slots in the array.
When there are empty slots in the array, then it is called a sparse array. This happens when you explicitly leave empty spaces when initializing the elements in a literal array, or when you assign the values at only some of the array indices.
The length property does not indicate the number of elements in the array when the array is sparsely populated. The length property will return one more than the highest index
If you view the array in the debugger, you can see that there are five empty slots before the value 'cat' at index 5, and 14 more empty slots before the value 'dog' at index 20.
JavaScript allows you to change the length of an array.
Setting the length of a dense array to a value greater than the length will make it a sparse array, and the length will no longer reflect the number of elements in the array.