6.6 Deleting Elements in an Array
We've already seen how to add elements to an array. Removing follows a symmetrical pattern: there are three methods, one for the end, one for the beginning, and one for any position in the middle. Take this array:
const numbers = [1, 2, 3, 4];
pop, shift and splice
numbers.pop()— removes the last element and returns it. After the call:[1, 2, 3]and the returned value is4.numbers.shift()— removes the first element and returns it. After the call:[2, 3]and the returned value is1.numbers.splice(index, count)— removescountelements starting atindex, anywhere in the middle.
const last = numbers.pop(); // 4 ; numbers is now [1, 2, 3]
const first = numbers.shift(); // 1 ; numbers is now [2, 3]
const arr = [1, 2, 3, 4];
arr.splice(2, 1); // remove 1 element at index 2 → [1, 2, 4]
arr.splice(0, 2); // remove 2 elements from index 0 → [4]
All three methods mutate the array in place. pop and shift also return the element they removed, which is handy when you want to keep a reference to it. splice can remove several elements at once by passing a count greater than 1.
To recap: pop for the end, shift for the beginning, splice for the middle. See you in the next video, where we'll see how to completely empty an array.