Skip to content
dreamcode
dreamcode
Map
Stacks & queues
Lesson 41 of 48
+15 XP on finish
JS ALGORITHMSChapter 8 · JS Algorithms

Stacks and Queues

A stack is last in, first out: push adds to the end and pop takes from the end, like a pile of plates. A queue is first in, first out: add with push and take from the front with shift. shift has to move every other item, so for big queues keep an index of the front instead. Stacks power undo and bracket matching; queues process work in arrival order.

Worked example

How it reads

  • pop returns the most recent item: the last action is undone first
  • shift returns the oldest item: first come, first served
  • Both change the original array
Cloud tip: Matching things in reverse order, like brackets or HTML tags, is a job for a stack.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Finish balanced with the stack so it prints true, false, false.

Press Run to check your work.