EN
JavaScript - remove last item from array
0
points
In this article, we would like to show you how to remove the last item from array using JavaScript.
1. Using splice() method
In this example, to remove the last element from the array we use splice() method.
// ONLINE-RUNNER:browser;
var array = ['a', 'b', 'c'];
array.splice(-1, 1); // splice(start, deleteCount)
console.log(array); // [a,b]
Note:
array.splice(-1, 1);is equal toarray.splice(array.length - 1, 1);.
2. Using pop() method
In this example, we use pop() method that removes the last element from array and returns that element.
// ONLINE-RUNNER:browser;
var array = ['a', 'b', 'c'];
array.pop();
console.log(array); // [a,b]
3. Using slice() method
In this example, we use slice() method to create a shallow copy of an array from indexStart to indexEnd (not included).
// ONLINE-RUNNER:browser;
var array = ['a', 'b', 'c'];
var newArray = array.slice(0, -1); // slice(indexStart, indexEnd)
console.log(newArray); // [a,b]
Warning:
This approach doesn't really remove the last element, it copies the array omitting it.