JavaScript Last Item in an Array

I have been a full-stack developer for twelve years and am currently part of the Cloud FinOps team at Atlassian. I previously ran an App development agency, managing various teams across design and development, leading web, backend and native mobile app developers in Australia and Europe. My strengths are system architecture design and communicating complicated tech to everyday people. Having helped scale tech at numerous startups, I am passionate about making a positive difference. When not working, you can find me writing tech articles and teaching Javascript and React at SheCodes, an initiative helping to get more women into tech. I regularly give talks on various topics, focusing on the impact the technology we build can have. I am devastated by the state of the world, love a good political rant and can often be swearing at no one in particular. I enjoy building things in JavaScript, Deno and Node.
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.




