Remove the last Element from an Array in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 06 20212 min read

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']

In the code snippet, we used the Array.pop method to remove the last element from the array.

If we call the Array.pop method 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.
Once you start mutating the same array multiple times, things get very confusing and difficult to debug.

We can create a copy of a subset of the array, by using the Array.slice method. This method does not change the contents of the original array.

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 parameters we passed to the slice method are:

  1. start index - a zero-based index at which we start extraction
  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.

This is good, because it's very difficult to keep tabs on how an array's contents change throughout your code once you start mutating it.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee