Remove the last Element from an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Remove the Last Element from an Array #

To remove the last element from an array, call the pop() method on the array, e.g. arr.pop(). The pop method removes the last element from the array and returns it. The method mutates the original array, changing its length.

index.js
const arr = ['a', 'b', 'c', 'd']; const removeLast = arr.pop(); console.log(removeLast); // 👉️ d console.log(arr); // 👉️ ['a','b','c']

We used the Array.pop method to remove the last element from the array.

If the Array.pop method is called on an empty array, it doesn't throw an error, instead it returns undefined.

index.js
const arr = []; const removeLast = arr.pop(); console.log(removeLast); // 👉️ undefined console.log(arr); // 👉️ []

Changing the contents of the array can be difficult to reason about, especially when you have to mutate the same array multiple times.

Most experienced developers avoid mutating arrays and objects, instead they create a copy of the array containing only the elements that are needed.

Alternatively, yuo can use the Array.slice method.

Use the Array.slice() method to remove the last element from an array, e.g. const withoutLast = arr.slice(0, -1);. The slice method will return a copy of the original array excluding the last element.

index.js
const arr = ['a', 'b', 'c', 'd']; const withoutLast = arr.slice(0, -1); console.log(withoutLast); // 👉️ ['a','b','c'] console.log(arr); // 👉️ ['a', 'b', 'c', 'd']

The Array.slice() method doesn't change the original array. Instead, the method returns a new array.

The parameters we passed to the slice method are:

  1. start index - the index of the first character to be included in the new array.
  2. end index - extract up to, but not including this index. A negative index of -1 means go up to, but not including the last element of the array
Passing an end index parameter of -1 and arr.length - 1 is the same. We instruct the slice method to go up to, but not including the last element of the array.

The benefit of this approach is that the contents of the original array remain unchanged.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.