The length of an array is often misunderstood as the tally of the number of items we’ve added to the array, when it’s not! It’s got something to do with the indices, actually.
Say, we create an array with two items. Its length will be shown as “2”. That’s expected, right? And as per the default, the first item is placed at index 0 of the array, and second one at index 1.
So far, so good. Now, add one more item at the index 8, and the length becomes — “9”!
As you can see, the length is computed based on the number of indices an array has, not the number of items we’ve added to it.
Adding an item at the index 8 of the array automatically creates the indices needed between the already present 0 & 1, and to be added, 8, to maintain a sequential list of indices. From 0 to 8, that’s a total of nine indices present in the array now, and hence the length, 9.
Indices are numerical properties of an array that can be looped through, and they are what we usually use to set data in the array and later access them. But arrays can also have other, non-index, properties, like this:
A description of the array is saved in a newly added
desc property. But as seen, the non-index properties are not taken into account while computing
length, only indices are. So the
length is still, 9.
Just as the number of indices present in an array affects the value of its
length property, it works vice-versa, too.
You change the value of the
length and that in turn affects the number of indices in the array.
Since we changed the
length to 5, the first five indices:0, 1, 2, 3, and 4 remain while the rest: 5, 6, 7, and 8 have all been removed now.
Instead of 5, If we’d given a larger length, larger than 8, then the array would’ve had more indices added to it.