Get the Last Item in an Array in JavaScript
Whether you’re pulling the most recent message, displaying the last product added to a cart, or checking the end of a result list, retrieving the final item in an array is used. In this tutorial, you’ll explore several techniques to access the last element in an array with detailed examples.
Method 1: Using array[array.length - 1]
This is the most widely used and reliable way to get the last item in an array. Because arrays in JavaScript are zero-indexed, the last element is always at length - 1
.
const colors = ["red", "green", "blue"];
const lastColor = colors[colors.length - 1];
console.log("Last color:", lastColor);
Last color: blue
Method 2: Using array.at(-1)
(ES2022+)
Introduced in ECMAScript 2022, the at()
method allows you to use negative indexing. This means -1
refers to the last element, -2
to the second last, and so on. It improves readability and reduces common off-by-one errors.
const colors = ["red", "green", "blue"];
const last = colors.at(-1);
console.log("Last color using at():", last);
Last color using at(): blue
Method 3: Using slice()
to Extract the Last Element
The slice()
method can extract a portion of an array without modifying the original. By passing -1
, you get a new array containing only the last item. Though slightly more verbose, this can be helpful when you want the result as an array.
const colors = ["red", "green", "blue"];
const lastItem = colors.slice(-1)[0];
console.log("Last item using slice:", lastItem);
Last item using slice: blue
Method 4: Using pop()
— With Caution
The pop()
method removes the last item from an array and returns it. Use this only when you're okay modifying (mutating) the original array. It’s great for stacks or temporary data structures.
let colors = ["red", "green", "blue"];
const last = colors.pop();
console.log("Last item using pop:", last);
console.log("Remaining array:", colors);
Last item using pop: blue
Remaining array: ["red", "green"]
When Should You Use Each Method?
array[array.length - 1]
: Ideal for universal support and quick access without mutation.array.at(-1)
: Great for modern codebases that favor clarity and readability.slice(-1)[0]
: Useful when you need a safe, non-mutating way to return a single-item array.pop()
: Best for stack-style logic where removing the last item is part of the process.
Comments
Loading comments...