Skip to content
Set, Map, and the Iteration Protocols
step 1/7

Reading — step 1 of 7

Learn

~3 min readCollections and Property Descriptors

Plain objects ARE often used as maps in JavaScript, but the built-in Map and Set (ES2015) are better for most cases. They preserve insertion order, accept any key type, and have a clean iteration API.

Set — unique values

javascript

From an array (with dedup):

javascript

This is the canonical JS dedup pattern.

Iterate Set:

javascript

Map — key/value pairs (any key type)

javascript

With initial entries:

javascript

Why prefer Map over plain object?

javascript

Map keys don't collide with prototype properties. Map preserves insertion order reliably across all JS engines. Map can have non-string keys.

Iterate Map:

javascript

When to use which

Use caseBest choice
Dedup a list[...new Set(arr)]
Membership check on a fixed listSet
Counter/frequency mapMap
Object-keyed lookupMap
Configuration / fixed-shape dataPlain object
JSON-serializable dataPlain object (Map doesn't JSON-serialize)

Iteration protocols (recap)

Anything that has [Symbol.iterator]() is iterable:

  • Strings
  • Arrays
  • Sets
  • Maps
  • Generators
  • TypedArrays
  • NodeList (DOM)
  • arguments

Iterables work with:

  • for...of
  • Spread [...iter], {...iter} (limited)
  • Destructuring [a, b] = iter
  • Array.from(iter)
  • Promise.all, Set and Map constructors

Plain objects are NOT iterable by default. Use Object.entries(obj), Object.keys(obj), Object.values(obj) to get an array.

Common mistakes

  • Plain object as a map with arbitrary string keys — collisions with __proto__, toString, constructor. Use Map or Object.create(null).
  • JSON.stringify on a Map — produces {}. Convert to a plain object first or use a custom replacer.
  • Set/Map for primitive lookups when you'd be fine with an object — slight overhead. For tiny fixed lists, plain object/array can be fine.
  • Comparing Sets with === — references. new Set([1]) === new Set([1]) is false. Compare contents manually.
  • Forgetting Sets dedupe by SameValueZeroSet treats NaN as equal to NaN (unlike ===), but objects are by reference.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…