Arrays come with built-in methods for adding and removing items at either end. There are four, and they come in pairs:
| Method | What it does | Gives back |
|---|---|---|
push(item) | Adds item(s) to the end | The new length |
pop() | Removes the last item | The removed item |
unshift(item) | Adds item(s) to the start | The new length |
shift() | Removes the first item | The removed item |
const queue = ["Mia", "Omar"];
queue.push("Zoe");
console.log(queue);
queue.unshift("Sam");
console.log(queue);
const last = queue.pop();
console.log(`Removed from the end: ${last}`);
console.log(queue);
const first = queue.shift();
console.log(`Removed from the start: ${first}`);
console.log(queue);
It prints
[ 'Mia', 'Omar', 'Zoe' ] [ 'Sam', 'Mia', 'Omar', 'Zoe' ] Removed from the end: Zoe [ 'Sam', 'Mia', 'Omar' ] Removed from the start: Sam [ 'Mia', 'Omar' ]
Picture a queue at the bank. When a new customer arrives, they join at the back of the line: that's push. When the cashier is ready, they serve the person at the front: that's shift. If the person at the back gets bored and leaves, that's pop. And if someone rude pushes in at the very front, well... that's unshift. (Don't be an unshift in real life.)
push and pop work on the end of the array, and they're by far the most common. If you only remember one method from this lesson, make it push. You'll use it constantly to build up lists.