Map and Set solve problems that plain objects and arrays don't handle well. WeakMap and WeakSet enable memory-safe private data. This article implements polyfills for the first two, and explains all four with runnable examples.
Prerequisites: JS Foundations #4 — Prototypes
1. Why We Need Map — The Problems with Objects as Dictionaries
Plain objects have key limitations: keys are always strings (or Symbols), and inherited properties collide with data:
Loading editor...
Map fixes this: any value (object, function, number) can be a key, and keys don't collide with inherited properties.
2. Implementing a Simple Map Polyfill
Loading editor...
3. Set — Unique Values
A Set stores unique values — duplicates are ignored:
Loading editor...
4. WeakMap — Garbage-Collectable Keys
WeakMap keys must be objects, and they're held weakly — if nothing else references the key, the entry is garbage collected. You can't iterate over a WeakMap:
Loading editor...
The main use case: storing private data associated with an object without preventing its garbage collection. This is how #private fields are polyfilled.
5. WeakSet — Weak Collection of Objects
Like WeakMap, WeakSet only stores objects weakly — no iteration, no size:
Loading editor...
6. Quick Comparison
Loading editor...
Key Takeaways
Mapallows any type as keys and preserves insertion order.Setstores unique values — ideal for deduplication.WeakMapholds objects weakly — use for private data tied to an object's lifetime.WeakMapandWeakSetare not iterable and have nosize— by design.WeakMapis the ES6 replacement forObject.create(null)with stronger guarantees.
Next: Prototypes #2 — Object.create() & instanceof Polyfills — implement both from scratch.
