How To Get The Last Entry In A Javascript Array - The Modern Way
September 29th, 2022
If you want to get the last item in a Javascript array you would need to do something like this:
const myArray = ['one', 'two', 'three', 'four']
const lastItem = myArray[(myArray.length - 1)]
Essentially getting the length of the array and then accessing the last item by the index.
Feels a bit messy, right?
There's now a cleaner way to get the last item in a Javascript array; using the Array.prototype.at()
method:
const myArray = ['one', 'two', 'three', 'four']
const lastItem = myArray.at(-1)
We're still getting the last item via its index, but this removes the need to get the length first.