How to remove the first or last element of an array in JavaScript?
Use shift to remove the first element and pop to remove the last, or slice and destructuring to get a new array without changing the original.
shift() removes the first element and pop() removes the last one. Both change the original array and return the element they removed.
const queue = ['a', 'b', 'c', 'd'];
const first = queue.shift(); // 'a'
const last = queue.pop(); // 'd'
console.log(queue); // ['b', 'c']On an empty array, both return undefined and don't throw.
Without changing the original
slice() returns a new array. A negative end index counts from the end, so slice(0, -1) means "everything except the last element":
const items = ['a', 'b', 'c', 'd'];
const withoutFirst = items.slice(1); // ['b', 'c', 'd']
const withoutLast = items.slice(0, -1); // ['a', 'b', 'c']
console.log(items); // ['a', 'b', 'c', 'd']When you need the first element and the rest, destructuring reads well:
const [first, ...rest] = items;
// first: 'a'
// rest: ['b', 'c', 'd']There's no destructuring version for the last element: const [...rest, last] = items is a syntax error, because the rest element has to come last.
This is the way to go with React state, where you shouldn't mutate:
setItems((items) => items.slice(1));To remove more than one element, pass a bigger number: items.slice(2) drops the first two, and items.splice(0, 2) removes them from the original.
Reading without removing
If you only need the value, don't remove anything:
items[0]; // 'a'
items.at(-1); // 'd'
items[items.length - 1]; // 'd'at() accepts negative indexes, which makes it the tidiest way to read the last element. items[-1] doesn't work: it looks for a property named "-1" and returns undefined.
shift() on large arrays
pop() is cheap, but shift() has to move every remaining element one position forward. That doesn't matter for normal arrays, but calling shift() in a loop over a large array, for example to process a queue, can get slow. Walk the array with an index instead:
// can be slow for large arrays
while (jobs.length > 0) {
runJob(jobs.shift());
}
// no copying
for (let i = 0; i < jobs.length; i++) {
runJob(jobs[i]);
}To remove an element from the middle of an array, see how to remove a specific element from an array.