Borislav Hadzhiev
Wed Oct 06 2021·2 min read
Photo by Sara Kurfeß
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.
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
.
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.
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.
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
means go up to, but not including the last element of the array-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.