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:
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
I would probably use this method even if I did know how many items were in the array. It’s clearer that I intend to get the last item.
If we used the index directly, how would we know that
49 is the right one? It could be in the middle of the array for all we know.
I hope this helps!
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!