JavaScript Last Item in an Array

JavaScript Last Item in an Array

The new method at allows you to return an item in an array at the given index. You might be thinking I can already do this with brackets. The great thing about at is it can take negative numbers and count back from the end of the array. The way at works gives you an easy way to get the last item in the array. Instead of array[array.length - 1] you can now do array.at(-1).

Here you can see how at works and how passing a negative number into the bracket method returns undefined.

const numbers = [5, 10, 15, 20, 25]

const firstNumber = numbers.at(0)
console.log(firstNumber) // 5

const last = numbers[-1]
console.log(last) // undefined

const lastNumber = numbers.at(-1)
console.log(lastNumber) // 25

With excellent browser support, nothing is stopping you from using it. Check the browser compatibility list for more info.