Finding the last element of an array in javascript

May 30, 2024·
Gert de Pagter
Gert de Pagter
· 2 min read

In javascript there is a few ways of getting the last item in an array. In this post we’ll go over them

Using Array.at()

Array.at has been available in the major browsers and node, since mid 2021 (except safari which introduced it in safari 15.4 in early 2022). With Array.at you can simply pass -1 to get the last element, or -2 to get the second to last element, and so on. Or if that item does not exist, for example with an empty array, or with an array with less than n elements, it returns undefined

const commands = ['add', 'commit', 'push', 'pull'];

console.log(commands.at(-1)); // 'pull'
console.log(commands.at(-2)); // 'push'
console.log(commands.at(-10)); // undefined

So if you are using node 16.6+, or do not support the older browsers where this function is not available, this is the easiest way to get the last element of an array in javascript

Legacy options

If Array.at() is not available to you, you can rely on using array.length -1 like so. It basically works the same as commands.at but is just a bit more verbose.

const commands = ['add', 'commit', 'push', 'pull'];

console.log(commands[commands.length - 1]); // 'pull'
console.log(commands[commands.length - 2]); // 'push'
console.log(commands[commands.length - 10]); // undefined

Note that commands[-1] will not work, as this tries to use the actual index of the string “-1”, which does not exist, and thus will return undefined.

Using Array.pop

The last option you have is Array.pop to get the last element of an array. pop comes with one major downside, in that it removes the element from the array. This means you modify your original array. So you want to be carefull of when you use this.

const commands = ['add', 'commit', 'push', 'pull'];

console.log(commands.pop()); // 'pull'

console.log(commands); // ['add', 'commit', 'push']

If you want to get notified of the next blog post, join the newsletter.