Sub topic 5
Adding and Removing Elements
This chapter assumes you can declare variables with const and let, write arrow functions, and use for loops. You should also know from the previous chapter that some methods mutate an array in place. Every method here does: push, pop, shift, unshift, and splice all change the original array.
Working at the Ends
JavaScript arrays have two ends, and each end has a method for adding and one for removing.
| Method | End | Effect | Returns |
|---|---|---|---|
| `push(...items)` | End | Adds items | New length |
| `pop()` | End | Removes one item | Removed item or `undefined` |
| `unshift(...items)` | Start | Adds items | New length |
| `shift()` | Start | Removes one item | Removed item or `undefined` |
const queue = ['a', 'b'];
console.log(queue.push('c', 'd')); // 4
console.log(queue); // ['a', 'b', 'c', 'd']
console.log(queue.pop()); // 'd'
console.log(queue.unshift('z')); // 4
console.log(queue.shift()); // 'z'
console.log(queue); // ['a', 'b', 'c']
console.log([].pop()); // undefined (no error)A common mistake is writing const list = items.push(x) and expecting list to hold the array. It holds a number, the new length.
Editing the Middle with splice
splice(start, deleteCount, ...items) removes deleteCount elements beginning at start, inserts any items in their place, and returns an array of the removed elements.
const letters = ['a', 'b', 'c', 'd'];
const removed = letters.splice(1, 2, 'x'); // replace
console.log(removed); // ['b', 'c']
console.log(letters); // ['a', 'x', 'd']
letters.splice(1, 0, 'y'); // insert only
console.log(letters); // ['a', 'y', 'x', 'd']
console.log(letters.splice(-1)); // ['d'] (negative start counts from the end)
console.log(letters); // ['a', 'y', 'x']If you leave out deleteCount, splice removes everything from start to the end. If you pass 0, it removes nothing and only inserts.
The Splice-in-a-Loop Bug
When you remove elements while looping forward, the loop skips items, because the elements after the removed one shift down by one index.
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] (the second 2 was skipped)
const fixed = [1, 2, 2, 3];
for (let i = fixed.length - 1; i >= 0; i--) {
if (fixed[i] === 2) fixed.splice(i, 1);
}
console.log(fixed); // [1, 3]Looping backward fixes it because removing an element only moves elements you have already visited. When you don't need to mutate the array, filter is usually clearer. It gets its own chapter.
Exercise
Given const arr = [10, 20, 30, 40, 50];, what do arr.splice(1, 3, 99) and arr contain afterward?
Show answer
The call returns [20, 30, 40], and arr becomes [10, 99, 50]. Three elements starting at index 1 were removed, and 99 was inserted in their place.
Exercise
What does const n = ['x'].unshift('w', 'v'); store in n, and what is the array's order afterward?
Show answer
n is 3, the new length. The array is ['w', 'v', 'x'], because unshift inserts all its arguments as a group and keeps their order.