In JavaScript—and many other programming languages—arrays are zero-indexed. This means their indices start counting from 0
instead of 1
. Imagine an array of 50
items, for example. Its indices would range from 0
to 49
.
If we know there are 50
items in the array, we can easily access the last item using its index, which would be 49
in this case:
var lastFruit = fruits[49];
But what if we don't know how many items there are?
Here's the trick:
The maximum index is always one less than the array's length
property.
This means that, for an array of unknown length, you can get the last item by subtracting 1
from its length
property:
var lastFruit = fruits[fruits.length - 1];
I would probably use this method even if I did know how many items were in the array, because it's clearer that I intend to get the last item.
I hope this helps!