AI Hints
JavaScript · Lesson 44 of 138

Adding and Removing

Push, pop, shift, unshift.

⏱ 2 min read▶ Video at 53:19🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Adding and Removing
From the video: Adding and Removing
  • 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.

app.jsjavascript
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);
Output
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.

MethodDoesEnd
push(x)addend
pop()removeend
unshift(x)addstart
shift()removestart

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.

app.jsjavascript
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);
}
Output
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
Next up: Looping Arrays — for...of