Sub topic 3
What Weak Collections Can Hold and What They Cannot Do
This chapter assumes you know the Map and Set APIs and the difference between primitive values and object references. It also assumes you know that the garbage collector frees an object once nothing reachable refers to it.
Allowed Keys and Limits
A weak collection holds its keys weakly. If the key is the only remaining reference to an object, that reference does not keep the object alive. The rules below follow from this:
- Keys of a WeakMap and values of a WeakSet must be objects or non-registered symbols. Primitives such as strings are rejected, because a primitive is never collected and so cannot be held weakly.
- Weak collections have no
size, no iteration, and noclear(). Their contents depend on when garbage collection runs, so a count or a listing would give results you could not predict.
const wm = new WeakMap();
try {
wm.set('id', 1);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(wm.size); // undefined
console.log(typeof wm[Symbol.iterator]); // 'undefined'WeakMap Fundamentals and Patterns
A WeakMap supports only set, get, has, and delete. Use it to attach data to an object you don't own without extending that object's lifetime. Caching is the most common use:
const cache = new WeakMap();
function getArea(rect) {
if (cache.has(rect)) return cache.get(rect);
const area = rect.width * rect.height;
cache.set(rect, area);
return area;
}
const box = { width: 4, height: 5 };
console.log(getArea(box)); // 20 (computed)
console.log(getArea(box)); // 20 (cached)A WeakMap keyed by this can also hold per-instance private data. The data disappears when the instance does. Modern code often uses #private fields for this instead.
WeakSet and Object Tagging
A WeakSet records whether an object has been seen. A common use is detecting cycles during a traversal:
const visited = new WeakSet();
function walk(node) {
if (visited.has(node)) return;
visited.add(node);
for (const child of node.children) walk(child);
}
const root = { children: [] };
root.children.push(root); // cycle
walk(root); // terminates
console.log(visited.has(root)); // trueWeakRef and FinalizationRegistry
WeakRef gives you a single weak handle, and you read it with deref(), which may return undefined. FinalizationRegistry runs a callback at some point after an object is collected. The spec does not guarantee when that happens, or that it happens at all. Use both only as a last resort.
Choosing the Right Collection
| Need | Use |
|---|---|
| Key/value pairs with any key type, counted or iterated | Map |
| Fixed, string-keyed record or JSON data | Plain object |
| Unique values, deduplication, set math | Set |
| Data attached to objects, freed with them | WeakMap |
| Marking objects as seen or processed | WeakSet |
Exercise
You need a cache keyed by user ID strings, and you must report how many entries it holds. Should you use a WeakMap? Why or why not?
Show answer
No. WeakMap rejects string keys with a TypeError, and it has no size. Use a Map and evict entries yourself.