How to remove the last element of array in JavaScript?
The array is a linear data structure. Removing the last element from the array might have two situations. We may want to remove the last element and change the original array.
Again, we may want to remove the last element and form a new array.
Remove last element and change original
const fruits = ['apple', 'orange', 'banana', 'tomato']; const changed = fruits.pop(); // Using pop method const modified = fruits.splice(-1); // Using splice method
Remove last element and do not change original
const fruits = ['apple', 'orange', 'banana', 'tomato']; const sliced = fruits.slice(0, -1); // Using slice method console.log(fruits); console.log(sliced);