Remove the Last Item From an Array in JavaScript
In this tutorial, we'll go through different ways to remove the final element in an array using examples and detailed explanation.
Method 1: Using pop()
The pop()
method is the most direct and widely used way to remove the last item from an array. It mutates the original array and returns the removed element. This method is ideal for scenarios where you’re modifying an array directly and don’t need to preserve the original version.
const fruits = ["apple", "banana", "cherry"];
const removedItem = fruits.pop();
console.log("Updated array:", fruits);
console.log("Removed item:", removedItem);
Updated array: ["apple", "banana"]
Removed item: cherry
Method 2: Using slice()
(Non-Mutating Approach)
If you don’t want to alter the original array — maybe you’re managing state in React or simply prefer immutable code — you can use the slice()
method to create a copy of the array without its last element. This method returns a new array and leaves the original untouched.
const fruits = ["apple", "banana", "cherry"];
const trimmedFruits = fruits.slice(0, -1);
console.log("Original array:", fruits);
console.log("New array:", trimmedFruits);
Original array: ["apple", "banana", "cherry"]
New array: ["apple", "banana"]
Method 3: Using Destructuring with Rest Syntax
For a functional and expressive style, especially in modern JavaScript, you can use array destructuring along with the rest operator to skip the last element and collect the remaining values into a new array.
const fruits = ["apple", "banana", "cherry"];
const withoutLast = ((arr) => arr.slice(0, -1))(fruits);
console.log("Array without last item:", withoutLast);
Array without last item: ["apple", "banana"]
When to Use Each Method
pop()
: Use when you want to remove the last item and mutate the original array. Great for stacks or undo operations.slice()
: Perfect when you need to preserve the original and work immutably, especially in functional or reactive programming.- Destructuring + slice: Best for readability and clean, expressive syntax when working in modern JavaScript environments.
Comments
Loading comments...