Learn JavaScript
❯ collections.weak_collections

WeakMap & WeakSet in JavaScript

$concept

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.

$how it works
1

Weak means collectible

Entries don't keep keys alive — drop all other references and the entry disappears on next collection.

2

Objects as keys only

Primitives are rejected — weakness is meaningless without garbage-collected referents.

3

No enumeration

No iterators, no size, no clear — contents are nondeterministically partial by design.

4

Metadata pattern

weakmap.set(obj, meta) attaches data to objects (DOM nodes!) that cleans itself up automatically.

$example
let meta = new WeakMap();
let user = { name: "Ada" };
meta.set(user, { visits: 1 });
console.log(meta.get(user).visits, meta.has(user));
Output
1 true
1Metadata attaches to user without altering the object itself.
2get retrieves visits: 1; has confirms presence.
3Null user elsewhere and this entry vanishes — zero cleanup code.
$use cases
DOM-node metadata that dies with its elements
Object-keyed memo caches that can't leak
Private instance data collected with its owner
Visited-marking in traversals without retention

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.