WeakMap & WeakSet in JavaScript
WeakMap and WeakSet hold object keys/values weakly — entries vanish when nothing else references the key, enabling caches and metadata that never leak. Constraints follow from weakness: keys must be objects, no iteration (entries may disappear anytime), no size, no clear.
Canonical uses: private data via WeakMap (instance → internals, garbage-collected with the instance), memoization keyed by objects, and visited-marking without preventing collection. For primitives or iteration needs, use Map/Set instead.
Weak means collectible
Entries don't keep keys alive — drop all other references and the entry disappears on next collection.
Objects as keys only
Primitives are rejected — weakness is meaningless without garbage-collected referents.
No enumeration
No iterators, no size, no clear — contents are nondeterministically partial by design.
Metadata pattern
weakmap.set(obj, meta) attaches data to objects (DOM nodes!) that cleans itself up automatically.
let meta = new WeakMap();let user = { name: "Ada" };meta.set(user, { visits: 1 });console.log(meta.get(user).visits, meta.has(user));Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.