To get the last item in an array in JavaScript, you can use one of these methods:
1. Using array.length - 1
(Most Common)
Access the last element directly via the arrayβs length
property:
const lastItem = array[array.length - 1];
Example:
const fruits = ["π", "π", "π₯"];
console.log(fruits[fruits.length - 1]); // "π₯"
Edge Case Handling:
const emptyArray = [];
console.log(emptyArray[emptyArray.length - 1]); // undefined (no error)
2. Using slice(-1)
Use slice(-1)
to get a new array containing the last item, then extract it:
const lastItem = array.slice(-1)[0];
Example:
const numbers = [10, 20, 30];
console.log(numbers.slice(-1)[0]); // 30
console.log(numbers.slice(-2)[0]); // 20 (second-last item)
Note:
slice(-1)
creates a new array (e.g.,[30]
), so this is slightly less efficient than direct indexing.
3. Using at(-1)
(Modern Browsers)
Use the at()
method (ES2022+) to directly access the last item with negative indexing:
const lastItem = array.at(-1);
Example:
const colors = ["red", "green", "blue"];
console.log(colors.at(-1)); // "blue"
console.log(colors.at(-2)); // "green"
Caveat:
- Not supported in Internet Explorer or older browsers (use a polyfill if needed).
4. Using pop()
(Not Recommended)
Use pop()
to remove and return the last item (mutates the original array):
const lastItem = array.pop(); // Removes the last item!
Example:
const animals = ["πΆ", "π±", "π»"];
const last = animals.pop();
console.log(last); // "π»"
console.log(animals); // ["πΆ", "π±"] (modified array)
Avoid This unless you explicitly want to modify the array.
Comparison Table
Method | Pros | Cons |
---|---|---|
array[length - 1] | Fast, universal, no mutation | Verbose syntax |
slice(-1)[0] | Readable, no mutation | Creates a new array |
at(-1) | Clean syntax, no mutation | Not supported in older browsers |
pop() | Short syntax | Mutates the array |
Best Practice
Use array[array.length - 1]
for broad compatibility, or array.at(-1)
in modern environments.
// Recommended approach
const array = [1, 2, 3];
const lastItem = array.at(-1) ?? array[array.length - 1];
console.log(lastItem); // 3