0 instead of
1. Imagine an array of
50 items, for example. Its indices would range from
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;
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
This means that, for an array of unknown length, you can get the last item by subtracting
1 from its
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!