Sub topic 14
WeakMap in Practice: Caches and Private Data
This chapter assumes you know the WeakMap API from the previous chapter (set, get, has, delete) and that WeakMap keys must be objects held weakly. It also assumes you are comfortable with ES classes. The focus here is on two patterns where a WeakMap is the right tool: caching computed results per object, and storing private data per instance.
Both patterns rely on the same property. A WeakMap links data to an object without keeping that object alive. When the rest of the program drops the object, the garbage collector can reclaim both the key and its value.
Pattern 1: A Per-Object Cache
Suppose a calculation is expensive and always gives the same result for the same object. You want to compute it once per object. A regular Map would work, but every object passed in would stay in memory for as long as the cache exists, so the cache would grow forever. A WeakMap cache does not have this problem.
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)Common errors with caches
- Mutating the key object. The cache is keyed by identity, not by contents. If
box.widthchanges later,getArea(box)still returns the old value. Use this pattern only for objects you treat as immutable, or delete the entry when the object changes. - Caching by primitive input. If the input is a string or number, a WeakMap throws a
TypeError. Use aMapwith an explicit size limit instead. - Expecting to inspect the cache. A WeakMap has no
sizeand cannot be iterated, so you cannot list or count cached entries.
Pattern 2: Private Per-Instance Data
Before class private fields (#field) existed, a module-level WeakMap was the standard way to hide instance state. Code outside the module cannot reach the WeakMap, so it cannot read or change the data.
const privateData = new WeakMap();
class Counter {
constructor() {
privateData.set(this, { count: 0 });
}
increment() {
const data = privateData.get(this);
data.count += 1;
return data.count;
}
}
const c = new Counter();
c.increment();
console.log(c.increment()); // 2
console.log(Object.keys(c)); // []When c becomes unreachable, its { count } record becomes collectable too, so the pattern does not leak memory.
WeakMap or `#private` fields?
| Need | Better choice |
|---|---|
| Private state inside your own class | `#private` fields |
| Attaching data to objects you do not own (DOM nodes, library objects) | WeakMap |
| Sharing hidden state across several classes or functions in one module | WeakMap |
| Brand checks such as "was this object made by my class?" | Either (`#x in obj` or `wm.has(obj)`) |
Exercises
Exercise
A function caches parsed results keyed by the input string using a WeakMap. What goes wrong, and what should you use instead?
Show answer
WeakMap.set throws a TypeError because strings are primitives and cannot be weak keys. Use a Map, ideally with an eviction policy such as a maximum size, because a Map holds its keys strongly and will otherwise grow without limit.
Exercise
You cache getArea(box) in a WeakMap, then set box.width = 10. What does getArea(box) return, and how would you fix it?
Show answer
It returns the stale value 20, because the cache is keyed by object identity and does not watch the object's properties. Call cache.delete(box) after changing the object, or treat cached objects as immutable.