Remove last element from array JavaScript
Let's see multiple ways to remove the last element from an array.
The last element is the element the most to the right on an array. e.g. 5 is the last element in [1, 3, 5]
.
Remove the last element from an array using pop (mutates array)
Explanation after the code.
const arr = [5, 6, 7];
const last = arr.pop();
console.log(last); // 7
console.log(arr); // [5, 6]
The array method pop
works as follows:
- The last element of the array is removed from the original array (changes original array)
- The last element of the array is returned
Remove the last element from an array using slice (doesn't mutate array)
The nice thing about slice is that it doesn't change the original array. Explanation after the code.
const arr = [8, 9, 10];
const newArr = arr.slice(0, -1);
console.log(newArr); // [8, 9]
console.log(arr); // [8, 9, 10] original unchanged
The array method slice(startIndex, endIndex)
works as follows:
- The
startIndex
parameter is the index where to start slicing the array - The
endIndex
parameter is the index where to stop slicing the array - The method returns a new array with a slice of the array without changing the original array.
- If the
endIndex
parameter is-1
, is like saying to slice until the index before last.
Remove the last element from an array using splice (mutates array)
Explanation below the code. Notice it's splice with a p, like gene splicing. Expect mutation!
const arr = [4, 5, 6];
const last = arr.splice(-1, 1);
console.log(last); // [6]
console.log(arr); // [4, 5]
The array method splice(startIndex, deleteCount)
works as follows:
- The
startIndex
parameter is the index where to start removing elements of the array - The
deleteCount
is the number of elements to remove - It changes the original array
- It returns an array with the elements removed
Performance notes
A good rule of thumb is to avoid thinking about performance if you don't have performance issues. Try to make the code readable and with minimum side effects and move on with your life.
Check this JavaScript performance and benchmarking talk.
Questions
What's the output?
const arr = [1, 2];
console.log(arr.pop(), arr);
What's the output?
const arr = [];
console.log(arr.pop());
What's the output?
const arr = [4, 8];
const res = arr.slice(0, -1);
console.log(arr, res);
What's the output?
const arr = [];
console.log(arr.slice(0, -1));
What's the output?
const arr = [4, 5, 6];
const res = arr.splice(-1, 1);
console.log(arr, res);
What's the output?
const arr = [];
const res = arr.splice(-1, 1);
console.log(arr, res);