35 min·advanced

Lesson 6

Stacks, queues, maps & sets

Build a practical mental model for stacks, queues, maps & sets and use it in working JavaScript.

By the end, you will be able to…

  • Explain stacks, queues, maps & sets in your own words
  • Use stacks, queues, maps & sets in a small program
  • Recognize and debug a common failure mode

Build the mental model

A stack is last-in-first-out (push/pop), a queue is first-in-first-out (push/shift). Set stores unique values with O(1) lookup; Map stores key-value pairs with any key type and O(1) lookup, unlike plain objects limited to string/symbol keys.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: 2 22

Why this matters

Picking the right structure — a Set for uniqueness checks, a Map for lookups keyed by non-string data — turns an awkward nested loop into one clean, fast operation.

Real-world example

A 'recently viewed items' feature that must stay unique and ordered is a textbook Set-backed structure.

Common mistakes

  • Using an array with .includes() for repeated membership checks instead of a Set
  • Forgetting Map preserves insertion order and accepts object keys, unlike plain objects
  • Confusing a stack's LIFO order with a queue's FIFO order

Try it yourself

Challenge

Write uniqueValues(list) using a Set to remove duplicates while preserving order.

Practice

Knowledge check

What is the key advantage of a Set over an array for membership checks?

Summary

Reach for Set for uniqueness/O(1) lookup, Map for flexible key-value lookup, and stacks/queues for ordered processing.