Removing the last element of an array in Javascript
📣 Sponsor
One of the most frequent operations we perform on an array is removing the last element. There are a few different ways to do this - but one of the most common is to use the pop()
method. Consider you have the following array:
let myArr = [ "🍎", "🍏", "🍐", "🍍" ];
To remove the last element, all we have to do is apply pop()
:
let myArr = [ "🍎", "🍏", "🍐", "🍍" ];
myArr.pop();
console.log(myArr); // [ "🍎", "🍏", "🍐" ]
Notice here that this removes the last element and modifies the original array. We have permanently changed the original array by using pop()
.
Another common method is to use the splice
method. Again, splice
will modify the original array, and works in much the same way. There is no real reason to use one over the other:
let myArr = [ "🍎", "🍏", "🍐", "🍍" ];
myArr.splice(-1);
console.log(myArr); // [ "🍎", "🍏", "🍐" ]
Finally, another way to accomplish this without changing the original array is to use slice
(not to be confused with splice
). slice()
differs from both pop()
and splice()
in that it makes a shallow copy of the original array. Removing the last element with slice
looks like this:
let myArr = [ "🍎", "🍏", "🍐", "🍍" ];
let newArr = myArr.slice(0, -1);
console.log(newArr); // [ "🍎", "🍏", "🍐" ]
console.log(myArr); // [ "🍎", "🍏", "🍐", "🍍" ]
Here, we store our sliced array in a new variable since and the original array remains unchanged. However, shallow copies have some quirks, such as sometimes leading to the original array changing - so it is not an independent copy. You can learn morea about shallow copies and how to create deep copies here.
You can also learn more about the slice method here.
More Tips and Tricks for Javascript
- Javascript Functions
- How to validate an email with Javascript
- How to Check if Object is Empty in JavaScript
- How JSON works in Javascript
- How Events work in Javascript
- Import, Export and Require in Javascript
- Checking if a value is a number in Javascript with isNaN()
- A Guide to Heaps, Stacks, References and Values in Javascript
- How to remove a specific item from an array
- Javascript Logical Statements and Loops