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 is 4.
  • numbers.shift() — removes the first element and returns it. After the call: [2, 3] and the returned value is 1.
  • numbers.splice(index, count) — removes count elements starting at index, 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.

Summary

This lesson covers three essential methods for removing elements from JavaScript arrays: pop() removes the last element, shift() removes the first element, and splice() removes elements from any position (single or multiple). Each method returns the removed element(s), enabling developers to handle array manipulation efficiently at different locations within the array.

Key points

  • pop() method removes and returns the last element from an array
  • shift() method removes and returns the first element from an array
  • splice() method removes one or more elements from any position by specifying the index and count
  • All three methods modify the original array directly
  • splice() is the most versatile, allowing removal from the middle of an array
  • Multiple elements can be removed by passing a higher count value to splice()

FAQ

What is the difference between pop() and shift()?

pop() removes the last element from an array, while shift() removes the first element. Both return the removed element, but they operate on opposite ends of the array.

How do you remove elements from the middle of an array?

Use the splice() method with two arguments: the index of the element to remove and the number of elements to delete. For example, splice(2, 1) removes one element at index 2.

Can you remove multiple elements at once?

Yes, using splice(). Pass the starting index and a number greater than 1 as the second argument. For instance, splice(2, 2) removes two elements starting at index 2.