Maps & Sets Drills

When to reach for Map and Set instead of {} and []. Object keys, dedupe, ordered iteration, and a tiny groupBy.

Step 1 of 6

Why Map and Set exist

For years, JavaScript developers used plain objects as dictionaries: const cache = {}; cache[key] = value;. That works for small things, but it has sharp edges:

  • Object keys are coerced to strings. {}[1] = "a" stores the key as the string "1".
  • Objects inherit keys like toString and constructor. Looking up cache.toString gives you a function, not undefined.
  • Iteration order is mostly insertion order, but integer-like string keys ("0", "1") are surfaced first, in numeric order. Subtle and surprising.

ES2015 added Map and Set to fix all of this. Use them whenever you need a real keyed collection or unique-set semantics.

Web Standard

Map iteration order is guaranteed to be insertion order, full stop. Plain objects iterate string-integer keys ("0", "1") first, then string keys in insertion order, then symbols. Use Map when order matters.

Learn more on MDN