Sub topic 8
Associating Data Without Leaking: WeakMap and WeakSet
This chapter assumes you know the earlier material: reachability from roots, how mark-and-sweep decides what to free, and the leak patterns from the previous chapter, especially unbounded caches. You should also be able to run Node.js from the command line. WeakRef and FinalizationRegistry are covered in a later chapter. This one is only about WeakMap and WeakSet.
The problem: side tables that never forget
You often need to attach extra data to an object you don't own. Examples include a DOM element from a library, a request object from a framework, or a parsed AST node. Changing the object itself is risky, so you keep a side table:
const clickCounts = new Map();
function trackClick(element) {
clickCounts.set(element, (clickCounts.get(element) ?? 0) + 1);
}A Map holds its keys strongly. Every element that passes through trackClick stays reachable from clickCounts, and so does its value. This holds even after the element is removed from the page and the rest of your code has forgotten it. The map is reachable from a root, so the collector marks everything inside it. The side table has become an unbounded cache.
You could delete entries by hand. That requires knowing exactly when each object's life ends, and that is the information you usually lack. A WeakMap hands the decision to the garbage collector.
What "weak" means
A WeakMap is a key-value collection whose keys are held weakly. An entry does not keep its key alive. When the key becomes unreachable from everywhere else, the engine may remove the entry and collect the key and its value together.
In the diagram, object A survives as long as the Map does. Object B survives only while el points to it. Once el is reassigned, nothing strong reaches B. The collector can then reclaim B and its value, and the WeakMap entry disappears.
Ephemerons: how the value is treated
Internally, V8 implements each WeakMap entry as an ephemeron, a pair with a conditional rule. During marking, the value is marked only if the key has already been marked through some other path. So:
- The
WeakMapnever keeps the key alive. - The value is kept alive only while the key is alive.
- A value that refers back to its own key does not create a leak. The back-reference only counts if the key is reached first, and the key cannot be reached through its own value.
The last rule matters. A naive "weak key, strong value" design would leak whenever the value pointed back at the key. Ephemerons prevent that, at the cost of extra marking work: the collector has to revisit ephemeron tables until no more keys get marked.
Map versus WeakMap
| Feature | `Map` | `WeakMap` |
|---|---|---|
| Key types | Any value | Objects and non-registered symbols |
| Keeps keys alive | Yes | No |
| Iterable (`keys`, `entries`, `for...of`) | Yes | No |
| `size` | Yes | No |
| `clear()` | Yes | No |
| Methods | `get`, `set`, `has`, `delete`, and more | `get`, `set`, `has`, `delete` only |
| Good for | Collections you enumerate or key by primitives | Metadata attached to objects you don't control |
The missing features follow from the design. If you could iterate a WeakMap or read its size, the output would depend on when the collector last ran. That would make garbage collection observable and program behavior non-deterministic. The specification removes those operations so the contents can never depend on GC timing.
Primitive keys are rejected for a related reason. The string "user-42" can be recreated at any time from nothing, so it can never become "unreachable" in any meaningful sense. Since ES2023, symbols created with Symbol() are allowed as keys because each one is unique and can be forgotten. Registered symbols from Symbol.for() are rejected because the global registry can always produce them again. You need Node.js 20+ or a current browser for symbol keys.
const wm = new WeakMap();
wm.set({}, "ok"); // fine
wm.set(Symbol("tag"), "ok"); // fine in ES2023+ engines
try {
wm.set("user-42", "nope");
} catch (err) {
console.log(err.constructor.name); // TypeError
}
try {
wm.set(Symbol.for("app"), "nope");
} catch (err) {
console.log(err.constructor.name); // TypeError
}Seeing the difference
The collector runs when it decides to, so you can't watch an individual entry vanish. You can compare heap usage, though. Save this as weak-vs-map.js and run it with node --expose-gc weak-vs-map.js. The flag exposes global.gc() so you can force a full collection.
function measure(label, store) {
global.gc();
const before = process.memoryUsage().heapUsed;
for (let i = 0; i < 100_000; i++) {
const key = { id: i }; // only the store refers to key
store.set(key, new Array(100).fill(i)); // roughly 800+ bytes per value
}
global.gc();
const after = process.memoryUsage().heapUsed;
const mb = ((after - before) / 1024 / 1024).toFixed(1);
console.log(`${label}: +${mb} MB retained`);
}
measure("Map", new Map());
measure("WeakMap", new WeakMap());The Map run keeps tens of megabytes. The WeakMap run keeps close to nothing, because no key outlives its loop iteration. Exact numbers vary by Node version and platform.
Practical uses of WeakMap
Per-object caches and memoization
Cache results that are computed from an object, keyed by the object itself. The cache shrinks automatically as inputs are discarded.
const summaryCache = new WeakMap();
function computeSummary(order) {
const total = order.items.reduce((sum, item) => sum + item.price * item.qty, 0);
return { itemCount: order.items.length, total };
}
function getSummary(order) {
let summary = summaryCache.get(order);
if (summary === undefined) {
summary = computeSummary(order);
summaryCache.set(order, summary);
}
return summary;
}
let order = { items: [{ price: 5, qty: 2 }, { price: 3, qty: 1 }] };
console.log(getSummary(order)); // { itemCount: 2, total: 13 }
console.log(getSummary(order) === getSummary(order)); // true, cached
order = null; // the order and its cached summary can now be collectedThe cache assumes order is not mutated after the first call. Weak keys solve the lifetime problem only. You still have to handle invalidation yourself.
Metadata on DOM nodes
This is browser code. Data attached through a WeakMap goes away when the element is removed and dropped, so detached nodes are not kept alive by your bookkeeping.
const elementState = new WeakMap();
function enhance(button) {
elementState.set(button, { clicks: 0 });
button.addEventListener("click", () => {
elementState.get(button).clicks += 1;
});
}
const btn = document.createElement("button");
btn.textContent = "Press";
document.body.append(btn);
enhance(btn);
// Later: btn.remove(); once no variable refers to btn, its state is collectable too.Private state
Before #private class fields existed, a module-level WeakMap was the standard way to keep per-instance private data. You will still see it in older libraries and in code that needs to attach private data to objects created elsewhere:
const secrets = new WeakMap();
class Account {
constructor(pin) {
secrets.set(this, { pin });
}
check(pin) {
return secrets.get(this).pin === pin;
}
}
const acct = new Account("1234");
console.log(acct.check("1234")); // true
console.log(Object.keys(acct)); // []For classes you write yourself, prefer #pin. It is faster and clearer, and the engine manages its lifetime in the same way.
WeakSet: membership without ownership
A WeakSet is a set of objects held weakly. It has only add, has, and delete. Use it to record a yes/no fact about an object without extending the object's life.
A common use is branding, where you mark objects your code created so you can recognize them later:
const genuine = new WeakSet();
class Token {
constructor(value) {
this.value = value;
genuine.add(this);
}
static isGenuine(obj) {
return genuine.has(obj);
}
}
const real = new Token("abc");
const fake = { value: "abc" };
console.log(Token.isGenuine(real)); // true
console.log(Token.isGenuine(fake)); // falseAnother use is a long-lived "already processed" marker, for example to avoid wrapping the same object twice:
const wrapped = new WeakSet();
function wrapOnce(obj) {
if (wrapped.has(obj)) return obj;
wrapped.add(obj);
obj.wrappedAt = Date.now();
return obj;
}For short-lived bookkeeping, such as cycle detection inside one traversal call, a plain Set is fine. The set becomes unreachable when the function returns. WeakSet only matters when the set outlives the objects it tracks.
Common mistakes
The key is kept alive elsewhere
A WeakMap only helps if nothing else holds the key. If the same objects also sit in an array, a Map, a closure, or an event listener, they stay alive. The WeakMap entry stays with them.
const meta = new WeakMap();
const allSeen = []; // strong references defeat the WeakMap
function register(obj) {
meta.set(obj, { registeredAt: Date.now() });
allSeen.push(obj); // obj now lives as long as allSeen does
}The value holds the key strongly through another path
Ephemerons handle a value that points to its own key. They don't help if the value is also stored somewhere strong. For example, a value registered in a global event bus or array keeps its key alive through that other path.
Expecting deterministic removal
Entries disappear when the collector runs, which might be much later or, for a short script, never. Don't write logic that depends on an entry being gone. If you need to know an object's life has ended, you need explicit teardown, such as a dispose() method or an AbortController.
Using it for primitive-keyed caches
A cache keyed by URL, user ID, or any other string cannot be a WeakMap. For those, bound the cache with a size limit or LRU eviction, or a time-to-live.
Needing to enumerate
If you need to list, count, or serialize the entries, a WeakMap is the wrong tool. Use a Map and manage removal explicitly.
Choosing the right structure
- Are the keys primitives? Use a
Mapwith a size or time limit. - Do you need to iterate or count entries? Use a
Mapwith explicit deletion. - Are the keys objects whose lifetime someone else controls, and you only need lookups? Use a
WeakMap, or aWeakSetif you only need membership. - Is it your own class's private data? Use
#privatefields.
Exercise
A library caches parsed results with const cache = new WeakMap(), keyed by config objects. Memory still grows without limit, and heap snapshots show old config objects retained. The code also does history.push(config) for an undo feature. Why does the WeakMap not help, and what are two ways to fix it?
Show answer
The history array holds every config object strongly. The configs stay reachable from a root, so their WeakMap entries and cached values stay too. One fix is to cap the history length so old configs drop out. Another is to store something other than the configs themselves in history, such as serialized snapshots or IDs, so the WeakMap is the only remaining reference.
Exercise
In the WeakMap entry wm.set(node, { owner: node, data: big }), the value refers back to its key. Once all outside references to node are gone, can node and big be collected? Explain using ephemeron semantics.
Show answer
Yes. An ephemeron's value is marked only after its key has been reached through some other path. Nothing outside the entry reaches node, so it is never marked. Its value is then never marked either. The back-reference from the value to node is never traced, so node, the value object, and big are all collectable.
Exercise
Why does WeakMap have no size property and no keys() method, and why does it reject "abc" and Symbol.for("abc") as keys while accepting Symbol("abc")?
Show answer
size and iteration would expose when the garbage collector ran, which would make program behavior depend on GC timing. Weak keys must be values that can become unreachable. A string or a registered symbol can always be recreated, from a literal or from the global registry, so it can never be truly unreachable. A symbol made with Symbol() is unique and can be forgotten, so it is allowed.