Sub topic 5
Adding and Removing Elements
This chapter covers the five built-in methods that change an array's contents in place: push, pop, shift, unshift, and splice. It assumes you can create arrays, index into them, and read length, and that you know the difference between mutating and non-mutating methods from the previous chapter. All five methods here mutate. They change the array you call them on, and every other reference to that array sees the change.
Each method answers two questions differently: where in the array it works, and what it returns. Most bugs with these methods come from getting the return value wrong.
The Five Methods at a Glance
| Method | Where it acts | What it returns |
|---|---|---|
| `push(...items)` | End, adds | New `length` |
| `pop()` | End, removes one | Removed element, or `undefined` if empty |
| `unshift(...items)` | Start, adds | New `length` |
| `shift()` | Start, removes one | Removed element, or `undefined` if empty |
| `splice(start, deleteCount, ...items)` | Anywhere, adds and/or removes | Array of removed elements (possibly empty) |
Working at the End: push and pop
push appends one or more elements and returns the new length. pop removes the last element and returns it. Together they turn an array into a stack, where the last item in is the first one out.
const stack = [];
console.log(stack.push('a')); // 1
console.log(stack.push('b', 'c')); // 3
console.log(stack.pop()); // 'c'
console.log(stack); // ['a', 'b']
console.log([].pop()); // undefined (no error on empty)A common mistake is to assign the result of push and expect an array back:
let list = [1, 2];
list = list.push(3);
console.log(list); // 3, the array is gonepush returns a number. If you want a new array that includes the extra item, use spread syntax ([...list, 3]) or concat. Those don't touch the original.
Pushing the contents of another array
If you pass push an array, it adds that array as a single nested element:
const base = [1, 2, 3];
base.push([4, 5]);
console.log(base); // [1, 2, 3, [4, 5]]
const base2 = [1, 2, 3];
base2.push(...[4, 5]);
console.log(base2); // [1, 2, 3, 4, 5]Spreading into push works fine for typical sizes. Every spread element becomes a function argument, though, and engines cap how many arguments a call can take. That cap is usually somewhere between tens of thousands and a few hundred thousand. For very large arrays, append in a loop or build a new array with concat.
Working at the Start: unshift and shift
unshift inserts elements at index 0 and returns the new length. shift removes the first element and returns it. If you pair push with shift, the array behaves as a queue, where the first item in is the first one out.
const queue = ['first', 'second'];
console.log(queue.unshift('zero')); // 3
console.log(queue.shift()); // 'zero'
console.log(queue); // ['first', 'second']
const nums = [1, 2];
nums.unshift(3, 4);
console.log(nums); // [3, 4, 1, 2] (argument order is preserved)The last line surprises people. unshift(3, 4) inserts the arguments as one block, so the result is [3, 4, 1, 2]. It is not the same as calling unshift(3) followed by unshift(4), which gives [4, 3, 1, 2].
The cost of working at the start
Arrays keep their elements at consecutive indexes. When you add or remove at the front, every other element has to move to a new index. So shift and unshift are O(n): their cost grows with the array's length. push and pop touch only the end and are O(1) amortized, meaning constant time on average. Small arrays won't show the difference. If you call shift in a loop over a queue with a million entries, the work grows quadratically.
Working Anywhere: splice
splice(start, deleteCount, ...items) is the general tool. It removes deleteCount elements starting at start, inserts items in their place, and returns an array of the removed elements. The arguments work like this:
startcan be negative. In that case it counts from the end, so-1means the last element.- If you leave out
deleteCount,spliceremoves everything fromstartto the end. - A
deleteCountof0means pure insertion. - If
startis past the end, it is clamped tolength.
const items = ['a', 'b', 'c', 'd', 'e'];
console.log(items.splice(2, 0, 'X')); // [] (insert only)
console.log(items); // ['a', 'b', 'X', 'c', 'd', 'e']
console.log(items.splice(-2, 1)); // ['d']
console.log(items); // ['a', 'b', 'X', 'c', 'e']
console.log(items.splice(1, 2, 'Y')); // ['b', 'X'] (replace two with one)
console.log(items); // ['a', 'Y', 'c', 'e']
console.log(items.splice(1)); // ['Y', 'c', 'e']
console.log(items); // ['a']Note that splice always returns an array, even when it removes a single element. To get the removed value itself, destructure it: const [removed] = arr.splice(i, 1);.
Removing by value
Arrays have no remove(value) method. The usual pattern is indexOf followed by splice, and you must check the index first:
function removeFirst(arr, value) {
const i = arr.indexOf(value);
if (i !== -1) arr.splice(i, 1);
return arr;
}
console.log(removeFirst(['x', 'y', 'z'], 'y')); // ['x', 'z']
console.log(removeFirst(['x', 'y', 'z'], 'q')); // ['x', 'y', 'z']Without the guard, a missing value gives indexOf a result of -1. Then splice(-1, 1) quietly removes the last element. Nothing throws, so this bug is easy to miss.
Other Ways People Remove Elements (and Why to Avoid Most)
The delete operator leaves holes
delete arr[i] removes the property but leaves length and the other indexes as they were. The result is a sparse array, which is an array with a hole in it:
const a = [1, 2, 3];
delete a[1];
console.log(a.length); // 3
console.log(1 in a); // false
console.log(a[1]); // undefinedMethods treat holes inconsistently. forEach and map skip them, but for...of returns them as undefined. Use splice(i, 1) instead.
Setting length truncates
Assigning a smaller length drops elements from the end. Assigning 0 empties the array in place, and every reference to it sees the change:
const shared = [1, 2, 3, 4];
const alias = shared;
shared.length = 2;
console.log(alias); // [1, 2]
shared.length = 0;
console.log(alias); // []This is different from shared = []. That reassigns the variable and leaves alias pointing to the old contents. It also only works with let, not const.
Removing While Looping
If you call splice inside a forward index loop, the elements after the removed one shift left, and the loop skips the next element:
const nums = [1, 2, 2, 3];
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 2) nums.splice(i, 1);
}
console.log(nums); // [1, 2, 3] (one 2 survived)Loop backward so that a removal only moves elements you have already visited:
const nums2 = [1, 2, 2, 3];
for (let i = nums2.length - 1; i >= 0; i--) {
if (nums2[i] === 2) nums2.splice(i, 1);
}
console.log(nums2); // [1, 3]If you don't need to mutate, nums.filter(n => n !== 2) is clearer and runs in a single pass. You'll see it in the chapter on filter.
Choosing a Method
Exercise
Given const arr = [10, 20, 30, 40];, what are the return value of arr.splice(1, 2, 'a', 'b', 'c') and the final contents of arr?
Show answer
It returns [20, 30], the two removed elements. arr becomes [10, 'a', 'b', 'c', 40], because two elements were removed at index 1 and three were inserted in their place.
Exercise
What does this log, and why? const xs = ['a', 'b', 'c']; xs.splice(xs.indexOf('z'), 1); console.log(xs);
Show answer
It logs ['a', 'b']. indexOf('z') returns -1, and splice(-1, 1) counts from the end, so it removes the last element. Always check for -1 before calling splice.
Exercise
Write a function moveToFront(arr, i) that moves the element at index i to the front of arr in place, using only the methods from this chapter.
Show answer
function moveToFront(arr, i) { const [item] = arr.splice(i, 1); arr.unshift(item); return arr; }. For example, moveToFront(['a', 'b', 'c'], 2) returns ['c', 'a', 'b'].