paint-brush
How to Remove the Last Element of a JavaScript Arrayโ€‚by@smpnjn
29,964 reads
29,964 reads

How to Remove the Last Element of a JavaScript Array

by Johnny SimpsonNovember 6th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The most common way to remove the last element is to use the `pop()` method. There are a few different ways to do this - but one of the most common is to remove it permanently. The other common method is the `splice` method, which modifies the original array. Using `slice() makes a [shallow copy] of an array, so it is not an independent copy of the original. The slice method is not the same way - but it makes a 'deep copy' of the array.
featured image - How to Remove the Last Element of a JavaScript Array
Johnny Simpson HackerNoon profile picture


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 more about shallow copies and how to create deep copies here.


You can also learn more about the slice method here.


Also Published here