How to get the last element of an array?
1. Via the index length - 1 (the classic way)
This is the most universal way, and it works everywhere
javascript
const fruits = ["apple", "banana", "cherry"];
const last = fruits[fruits.length - 1];
console.log(last); // "cherry"lengthis the array's length.- Since indexing starts at
0, the last element sits at indexlength - 1.
2. Via the .at(-1) method (modern, ES2022+)
A nicer and more readable way
javascript
const fruits = ["apple", "banana", "cherry"];
console.log(fruits.at(-1)); // "cherry"Advantages:
-
You can use negative indexes, like in Python.
-
Works with both arrays and strings:
javascript"hello".at(-1); // "o"
Supported in Node.js 16+ and modern browsers.
3. Using .slice(-1)
javascript
const fruits = ["apple", "banana", "cherry"];
console.log(fruits.slice(-1)); // ["cherry"]
console.log(fruits.slice(-1)[0]); // "cherry"slice(-1)returns a new array with the last element.- To get the element itself, you need
[0].
4. Using destructuring (ES6+)
If you need to pull out the last element elegantly
javascript
const fruits = ["apple", "banana", "cherry"];
const [last] = fruits.slice(-1);
console.log(last); // "cherry"In short:
| Method | Code | Returns | Note |
|---|---|---|---|
| Index | arr[arr.length - 1] | element | works everywhere |
.at(-1) | arr.at(-1) | element | modern |
.slice(-1)[0] | element | creates a new array | |
| Destructuring | const [last] = arr.slice(-1) | element | elegant, ES6 |
Conclusion: For cross-browser compatibility, use
arr[arr.length - 1]. For modern code,arr.at(-1)looks much cleaner.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.