Sub topic 14
WeakMap in Practice: Caches and Private Data
This chapter assumes you already know the WeakMap API (set, get, has, delete), that WeakMap keys must be objects (or non-registered symbols), and that a WeakMap does not keep its keys alive. It covers the two patterns WeakMap was built for: caching computed results per object, and storing private data per instance. For each pattern it also covers the mistakes that make it fail.
The Core Idea: Data Attached Beside an Object
Both patterns work the same way. You store extra information about an object without writing to the object, and that information should disappear when the object disappears. A WeakMap gives you exactly this lifetime. An entry stays available for as long as its key object is reachable. After the key becomes unreachable, the garbage collector may remove the entry.
A WeakMap entry behaves like an ephemeron: the value is reachable only through the key. If the value holds a reference back to its own key, that reference does not keep the key alive. In a regular Map, the same back-reference would never cause a leak either, but the Map itself would hold the key strongly and keep it alive.
Pattern 1: Per-Object Caches
A basic cache
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)If you replaced WeakMap with Map, every rectangle ever passed to getArea would stay in memory for the life of the program. The Map holds a strong reference to each key, so no rectangle could ever be collected. With a WeakMap, once box goes out of scope everywhere else, both the rectangle and its cached area can be reclaimed.
Why check `has` instead of the result of `get`
A common shortcut is const hit = cache.get(obj); if (hit) return hit;. This version breaks whenever the cached result is falsy, such as 0, '', false, or undefined. Those results get recomputed on every call. Calling has first separates "no entry" from "an entry whose value is falsy".
A reusable memoizer
function memoizeByObject(fn) {
const cache = new WeakMap();
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
return fn(obj); // primitives cannot be WeakMap keys; skip caching
}
if (cache.has(obj)) return cache.get(obj);
const result = fn(obj);
cache.set(obj, result);
return result;
};
}
let calls = 0;
const countKeys = memoizeByObject((o) => {
calls += 1;
return Object.keys(o).length;
});
const config = { a: 1, b: 2 };
console.log(countKeys(config)); // 2
console.log(countKeys(config)); // 2
console.log(calls); // 1
console.log(countKeys(null)); // TypeError from Object.keys, not from the WeakMapThe guard matters because cache.set('text', ...) throws a TypeError. Without the guard, a primitive argument would fail inside the cache code with a confusing error. With the guard, primitives skip the cache, and any error comes from fn itself. The last line above shows this: Object.keys(null) throws its own TypeError.
Caching on more than one object
When a result depends on two objects, nest the WeakMaps. The outer map is keyed by the first object, and each inner map is keyed by the second.
const pairCache = new WeakMap();
function distance(a, b) {
let inner = pairCache.get(a);
if (!inner) {
inner = new WeakMap();
pairCache.set(a, inner);
}
if (inner.has(b)) return inner.get(b);
const d = Math.hypot(a.x - b.x, a.y - b.y);
inner.set(b, d);
return d;
}
const p = { x: 0, y: 0 };
const q = { x: 3, y: 4 };
console.log(distance(p, q)); // 5
console.log(distance(p, q)); // 5 (cached)If p is collected, its whole inner map goes with it. If only q is collected, its entry disappears from each inner map that held it. Note that distance(q, p) is a separate entry. If the computation is symmetric, normalize the argument order yourself.
The stale-cache trap
A WeakMap cache knows which object it was given. It does not know whether that object has changed.
const areaCache = new WeakMap();
function area(r) {
if (!areaCache.has(r)) areaCache.set(r, r.width * r.height);
return areaCache.get(r);
}
const r = { width: 2, height: 3 };
console.log(area(r)); // 6
r.width = 10;
console.log(area(r)); // 6 (stale: should be 30)What a WeakMap cache cannot do
A WeakMap has no size and no iteration, and you cannot control when entries leave it. That rules out several common cache features:
- No eviction policy. You cannot build LRU or max-size limits, because you cannot list or count entries.
- No time-based expiry unless you store timestamps in the values and check them on each read.
- No sharing between equal-looking inputs. Two separate
{ width: 4, height: 5 }objects are two separate entries. If your callers build fresh objects on every call, the cache never hits. In that case, key a regular Map by a derived primitive such as `${w}x${h}`, and add your own size limit.
Pattern 2: Private Per-Instance Data
The WeakMap approach
Before #private fields existed, a module-scoped WeakMap was the standard way to hide instance state. This pattern still appears in older libraries and transpiled code.
const internals = new WeakMap();
class Account {
constructor(owner) {
internals.set(this, { owner, balance: 0 });
}
deposit(amount) {
const data = internals.get(this);
if (!data) throw new TypeError('Not an Account');
data.balance += amount;
return data.balance;
}
static isAccount(value) {
return internals.has(value);
}
}
const acct = new Account('Ada');
acct.deposit(50);
console.log(acct.deposit(25)); // 75
console.log(Object.keys(acct)); // []
console.log(Account.isAccount(acct)); // true
console.log(Account.isAccount({})); // false
const fake = Object.create(Account.prototype);
try {
fake.deposit(1);
} catch (err) {
console.log(err.message); // 'Not an Account'
}Code outside the module cannot reach internals, so no outside code can read or change balance. The has check also works as a brand check: it shows that an object really went through the constructor and did not just inherit the prototype.
Comparing the options
| Technique | Truly hidden | Brand check | Works on objects you don't own | Collected with instance |
|---|---|---|---|---|
| `_underscore` property | No | No | Yes, but mutates them | Yes |
| Symbol-keyed property | No (`Object.getOwnPropertySymbols`) | No | Yes, but mutates them | Yes |
| `#private` field | Yes | Yes (`#x in obj`) | No, only own class instances | Yes |
| Module-scoped WeakMap | Yes | Yes (`wm.has(obj)`) | Yes, without mutation | Yes |
For your own classes, prefer #private fields. They are shorter, the engine optimizes them, and they need no get call on every access. The WeakMap approach still wins when you need to attach private state to objects you did not create: DOM nodes, objects from a third-party library, or frozen objects, which cannot gain new properties at all.
const meta = new WeakMap();
const frozen = Object.freeze({ id: 7 });
meta.set(frozen, { seenAt: Date.now() });
console.log(meta.has(frozen)); // true; the frozen object itself was never touchedGotchas with the private-data pattern
- Subclasses share the map. A subclass constructor calls
super(), which sets the entry with the subclass instance as key. This is usually what you want. Do not callinternals.set(this, ...)again in the subclass, because it replaces the parent's record. - Proxies break the brand check.
new Proxy(acct, {})is a different object, sointernals.get(proxy)returnsundefined.#privatefields fail the same way. - Debugging is harder. DevTools shows WeakMap entries, but nothing appears on the instance itself. Logging
acctshows an empty object.
Exercise
A team caches parsed results with const cache = new WeakMap() keyed by request objects. The hit rate is 0%, but the code has no errors. Each call does parse({ url: req.url, body: req.body }). What is wrong, and how would you fix it?
Show answer
Each call builds a new object, and WeakMap compares keys by identity, so no key is ever looked up twice. Either pass the original long-lived req object as the key, or switch to a Map keyed by a primitive derived from the data (for example the URL plus a hash of the body) and add a size limit, because that Map holds its keys strongly.
Exercise
Why does the memoizer return fn(obj) directly for primitives instead of calling cache.set, and why does it check cache.has before cache.get?
Show answer
WeakMap.prototype.set throws a TypeError for primitive keys, so primitives must skip the cache. Checking has first separates a missing entry from a cached falsy result such as 0 or undefined. Checking the result of get alone would recompute those results on every call.
Exercise
You need to record which objects returned by a third-party library have already been validated, along with the time each validation happened. The library freezes its objects. Should you use a #private field, a Symbol property, or a WeakMap?
Show answer
Use a WeakMap. You cannot add a #private field to objects your class did not construct. You cannot add a Symbol property to a frozen object, and it would not be hidden anyway. A WeakMap keyed by each object, with a value like { validatedAt: Date.now() }, leaves the objects untouched and lets the records be collected along with them.