DEV Community

Cover image for How to get the last element of an Array in Javascript
Johnny Simpson
Johnny Simpson

Posted on β€’ Originally published at fjolt.com

18

How to get the last element of an Array in Javascript

So you have a Javascript array, and you want to get the last element. Take this example, for instance:

let myArray = [ 'πŸ”©', '⚑️', 'πŸ”‘', 'πŸ–‡' ]
Enter fullscreen mode Exit fullscreen mode

This array has 4 items - and as you might know, to get any element within it, we can use the square bracket notation []. For example, to get the lighting bolt, we can use myArray[1]:

let myArray = [ 'πŸ”©', '⚑️', 'πŸ”‘', 'πŸ–‡' ]
console.log(myArray[1]) // ⚑️
Enter fullscreen mode Exit fullscreen mode

Since arrays start at an index of 0, the first element is actually myArray[0], and so on. So to get the last element of the array, we can use myArray.length - 1. This gets the length of the array (4), and subtracts 1, to take into consideration that arrays start counting at 0. Therefore, to get the last element of an array using the square bracket notation, we can do something like this:

let myArray = [ 'πŸ”©', '⚑️', 'πŸ”‘', 'πŸ–‡' ]
console.log(myArray[myArray.length-1]) // πŸ–‡
Enter fullscreen mode Exit fullscreen mode

This is the most common way to get the last element of an array. However, you can also use the at method to do the same thing:

let myArray = [ 'πŸ”©', '⚑️', 'πŸ”‘', 'πŸ–‡' ]
console.log(myArray.at(myArray.length-1)) // πŸ–‡
Enter fullscreen mode Exit fullscreen mode

And even better, you can simply write myArray.at(-1)! This greatly simplifies getting the last element of an array to a simple expression:

let myArray = [ 'πŸ”©', '⚑️', 'πŸ”‘', 'πŸ–‡' ]
console.log(myArray.at(-1)) // πŸ–‡
Enter fullscreen mode Exit fullscreen mode

As you might expect, at starts counting backwards, so at(-2) will return the key:

let myArray = [ 'πŸ”©', '⚑️', 'πŸ”‘', 'πŸ–‡' ]
console.log(myArray.at(-2)) // πŸ”‘
Enter fullscreen mode Exit fullscreen mode

Neon image

Serverless Postgres in 300ms (!)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free β†’

Oldest comments (2)

Collapse
 
kosm profile image
Kos-M β€’

Nice!

Collapse
 
mathcoll profile image
Mathieu Lory β€’

Another way to do it .. this way will change the input
let myArray = [ 'πŸ”©', '⚑️', 'πŸ”‘', 'πŸ–‡' ]
console.log(myArray.pop()) // πŸ”‘

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️