Removing elements from arrays
Learn to remove elements from the end and start of an array with pop and shift.
Removing from the end with pop
The pop method removes the last element of the array and returns that element. The array shrinks.
Example: with const fruits = ["apple", "pear", "banana"];, calling fruits.pop(); returns "banana" and leaves ["apple", "pear"].
To keep the removed element, assign the return value: const last = fruits.pop();.
Removing from the start with shift
The shift method removes the first element of the array and returns it. The other elements shift one index toward the start.
Example: with const colors = ["red", "blue", "green"];, calling colors.shift(); returns "red" and leaves ["blue", "green"].
Calling shift or pop on an empty array returns undefined; no error is thrown.
Exercise Remove elements from the queue array
Create an array named queue with three strings. First remove the first element with shift, then remove the last element with pop. Finally print the array length with console.log.
Show example solution
Define a queue array with three strings, remove from start and end, then print the length.
Example solution:
const queue = ["a", "b", "c"];
queue.shift();
queue.pop();
console.log(queue.length);
Test yourself
-
Which describes the behavior of the shift method?
- removes from start
- removes from end
- appends to end
- prepends to start
Show answer
removes from start — Correct. shift removes the first element of the array.
-
Remove and store the last element from the stack array
const stack = ["a", "b", "c"]; const last = stack.____; console.log(last);Show answer
const stack = ["a", "b", "c"]; const last = stack.pop(); console.log(last); -
Match the removal methods
- pop
- removes the last element
- shift
- removes the first element
- pop()
- returns the removed element