Get Last Array Item in JavaScript
- 1 minute read
In JavaScript, you could grab the last item of an array like this:
const array = [`a`, `b`, `c`, `d`];
const lastItem = array[array.length - 1];
This approach is fine and all, but there is a slightly cleaner way which utilizes JavaScript’s Array.slice() method:
const array = [`a`, `b`, `c`, `d`];
const lastItem = array.slice(-1);
The neat thing about the above approach is that you don’t need to know the length of the array to grab the last item.
You can also grab the second-to-last item by passing -2
instead of -1
to slice()
, and so on:
const array = [`a`, `b`, `c`, `d`];
const lastItem = array.slice(-2);
However, you must ensure that the number you pass to slice does not exceed the length of the array! Otherwise, an error will be thrown.
Conclusion
Anyway, I’ve found this approach to be a clean way to grab the last item in a JavaScript array. However, I’m not entirely sure whether it is more performant.