Adding and Removing
Push, pop, shift, unshift.
Lists grow and shrink. Add a song to the playlist, or remove the first person from a queue. Four methods handle the two ends of an array.

- Lists grow and shrink
- The two ends
- Four methods
Both ends
Push adds to the end, and pop removes from the end, returning what it removed. Unshift adds to the start, and shift removes from the start. Run it. Watch the queue change after each step.
const queue = ["Ana", "Ben"];
queue.push("Cara");
console.log("push:", queue);
const last = queue.pop();
console.log("pop:", last, queue);
queue.unshift("Zoe");
console.log("unshift:", queue);
const first = queue.shift();
console.log("shift:", first, queue);push: [ 'Ana', 'Ben', 'Cara' ] pop: Cara [ 'Ana', 'Ben' ] unshift: [ 'Zoe', 'Ana', 'Ben' ] shift: Zoe [ 'Ana', 'Ben' ]
The four methods
Push and pop work on the end of the array. Shift and unshift work on the start. Push and pop are very fast. Shift and unshift are slower on big arrays, because every other item has to move along by one place.
| Method | Does | End |
|---|---|---|
| push(x) | add | end |
| pop() | remove | end |
| unshift(x) | add | start |
| shift() | remove | start |
A to-do queue
Push and shift together make a queue. The first item added is the first one out, like a line at a shop. Here new tasks join the end with push, and we work through them from the front with shift, until the array is empty. Run it.
const tasks = [];
tasks.push("wash dishes");
tasks.push("reply to email");
tasks.push("water plants");
while (tasks.length > 0) {
const next = tasks.shift();
console.log("Doing:", next, "| left:", tasks.length);
}Doing: wash dishes | left: 2 Doing: reply to email | left: 1 Doing: water plants | left: 0
Summary
Push and pop change the end of an array, and unshift and shift change the start. Next, looping through arrays.
Key takeaways- push / pop
- unshift / shift
- pop returns the item