Array Methods

Removing Elements

🙋 Need help? Ask an expert now!

As mentioned previously, all arrays in JavaScript are dynamic, meaning elements can be removed from the array. The methods pop() and shift() are two methods that remove elements from an array. Take a look at how the method functions and the syntax below.

arrayname.pop()

  • Removes the element at the tail
  • Returns the removed element

arrayname.shift()

  • Removes the element at the head
  • Returns the remove element

The pop() and shift() methods are methods that don't need to be called with a specific parameter. The pop() method removes the last element while the shift() method removes the first element of the array. Calling the pop() method removed the last element 5, which is why version 1 of the array is [1,2,3,4]. Calling the shift() method then removed the first element of the array, which is why version 2 of the array is [2,3,4]. These two methods are not the same, and are to be used when appropriate.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [1, 2, 3, 4, 5];
            arr.shift();
            arr.pop();
            console.log(arr);
            

What will the following code segment print to the console?