How to get the last element of an Array in Javascript
📣 Sponsor
So you have a Javascript array, and you want to get the last element. Take this example, for instance:
let myArray = [ '🔩', '⚡️', '🔑', '🖇' ]
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]) // ⚡️
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]) // 🖇
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)) // 🖇
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)) // 🖇
As you might expect, at
starts counting backwards, so at(-2)
will return the key:
let myArray = [ '🔩', '⚡️', '🔑', '🖇' ]
console.log(myArray.at(-2)) // 🔑
More Tips and Tricks for Javascript
- How to check if a user has scrolled to the bottom of a page with vanilla Javascript
- Javascript Proxy: Using Javascript Proxies like a Pro
- How Events work in Javascript
- Detecting Device Orientation with Javascript
- How to install nvm, the Node Version Manager
- The Many Quirks of Javascript Dates
- How does Optional Chaining work in Javascript?
- Javascript: Check if an Array is a Subset of Another Array
- Setting the Default Node.JS version with nvm
- Javascript on Click Confetti Effect