JavaScriptMedium
What is WeakMap?
A WeakMap is a key-value collection whose keys must be objects (or non-registered symbols) and are held weakly: an entry does not stop its key from being garbage-collected, and once the key is gone the entry disappears automatically.
Differences from Map
Map | WeakMap | |
|---|---|---|
| Keys | Any value | Objects (and non-registered symbols) only |
| Keeps keys alive | Yes | No |
Iterable / size | Yes | No |
| Methods | get, set, has, delete, clear, iteration | get, set, has, delete |
It cannot be iterated or sized because its contents can change whenever the garbage collector runs.
Use cases
- Attaching data to objects you don't own (DOM nodes, library objects) without modifying them and without causing leaks.
- Caching results per object: memoise computations keyed by an object; the cache entry dies with the object.
- Private data for classes (the pre-
#privatetechnique). - Tracking which objects have already been processed.
When to use something else
- Need to list or count entries, or use primitive keys: use
Map. - Just need to remember objects (no value): use
WeakSet. - Need to hold an object weakly and check later whether it is still alive:
WeakRef.
Code example
js
1// Cache expensive per-object results without leaking memory2const sizeCache = new WeakMap();3function expensiveSize(obj) {4 if (sizeCache.has(obj)) return `${sizeCache.get(obj)} (cached)`;5 const size = JSON.stringify(obj).length; // pretend this is expensive6 sizeCache.set(obj, size);7 return size;8}910let report = { rows: Array.from({ length: 100 }, (_, i) => ({ i })) };11console.log(expensiveSize(report)); // computed12console.log(expensiveSize(report)); // "... (cached)"13report = null; // the cache entry can be collected along with the object1415// Attach metadata to objects you don't own16const clickCounts = new WeakMap();17const button = { id: "buy" }; // imagine a DOM element18clickCounts.set(button, (clickCounts.get(button) ?? 0) + 1);19clickCounts.set(button, clickCounts.get(button) + 1);20console.log(clickCounts.get(button)); // 22122// Keys must be objects23try {24 new WeakMap().set("text", 1);25} catch (e) {26 console.log(e.name); // TypeError27}2829// No size or iteration30console.log(typeof new WeakMap().size, typeof new WeakMap()[Symbol.iterator]); // undefined undefined
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.