How to get the last item in a JavaScript array

In JavaScript, 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. 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!