Data #3 — Map, Set, WeakMap, WeakSet Polyfills

Implement Map (hash map), Set, WeakMap (garbage-collectable keys), and WeakSet — understand when to use each over plain objects and arrays.

11 min read
JavaScript
Data
ES6
Polyfill

TABLE OF CONTENTS
Data #3 — Map, Set, WeakMap, WeakSet Polyfills

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

  • Map allows any type as keys and preserves insertion order.
  • Set stores unique values — ideal for deduplication.
  • WeakMap holds objects weakly — use for private data tied to an object's lifetime.
  • WeakMap and WeakSet are not iterable and have no size — by design.
  • WeakMap is the ES6 replacement for Object.create(null) with stronger guarantees.

Next: Prototypes #2 — Object.create() & instanceof Polyfills — implement both from scratch.


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI