Sub topic 8
Associating Data Without Leaking: WeakMap and WeakSet
This chapter assumes you know how reachability decides what the garbage collector keeps, and that you have seen how an unbounded cache can leak. It shows how to attach extra data to objects you don't own without keeping those objects alive.
The problem with Map as a side table
You often need to store information about an object without changing the object itself. Examples include a DOM node, a request object, or an instance from a library. A Map keyed by the object seems like the obvious tool. The catch is that a Map holds its keys strongly. Each entry is a reference from a reachable structure, so the key stays reachable for as long as the map does.
const clickCounts = new Map();
function track(element) {
clickCounts.set(element, (clickCounts.get(element) || 0) + 1);
}
let button = { id: "save" };
track(button);
button = null;
// The object is still reachable through clickCounts.
console.log(clickCounts.size); // 1If elements come and go over time, this map grows forever unless you remember to call delete for each one.
How WeakMap changes reachability
A WeakMap holds its keys weakly. An entry does not count toward the key's reachability. Once nothing else references the key, the collector can free the key and drop its value along with it.
The value is held strongly only while its key is alive. In engine terms this pairing is called an ephemeron.
const clickCounts = new WeakMap();
function track(element) {
clickCounts.set(element, (clickCounts.get(element) || 0) + 1);
}
function countFor(element) {
return clickCounts.get(element) || 0;
}
let button = { id: "save" };
track(button);
track(button);
console.log(countFor(button)); // 2
button = null;
// No strong references remain, so the key and its count can be collected.WeakSet: marking objects
A WeakSet is the set version of the same idea. It answers "have I seen this object?" without keeping the object alive. A common use is detecting cycles while walking a graph:
function hasCycle(node, seen = new WeakSet()) {
if (node === null || typeof node !== "object") return false;
if (seen.has(node)) return true;
seen.add(node);
const found = Object.values(node).some((child) => hasCycle(child, seen));
seen.delete(node);
return found;
}
const a = {};
const b = { a };
a.b = b;
console.log(hasCycle(a)); // true
console.log(hasCycle({ x: { y: 1 } })); // falseThe restrictions, and why they exist
| Feature | Map / Set | WeakMap / WeakSet |
|---|---|---|
| Key types | Any value | Objects and non-registered symbols only |
| Iteration, `keys()`, `forEach` | Yes | No |
| `size` | Yes | No |
| `clear()` | Yes | No |
| Keeps keys alive | Yes | No |
These limits all come from the same cause. Collection timing is non-deterministic, so if you could iterate or count the entries, the result would change depending on when the collector last ran. Primitive keys such as "id" or 42 are rejected because a primitive can always be recreated, so the entry could never safely disappear.
Common errors
- Using a WeakMap as a general cache keyed by strings. This throws
TypeError: Invalid value used as weak map key. Use aMapwith an eviction policy instead. - Expecting memory to drop immediately after setting a key to
null. The entry goes away only when the collector runs. - Trying to debug by logging the contents. You can't enumerate entries, so check specific keys with
hasorget.
Exercise
You store per-request metadata in const meta = new Map() keyed by request objects, and memory climbs steadily under load. What one-line change fixes the leak, and what capability do you lose?
Show answer
Change it to const meta = new WeakMap(). Entries then disappear when their request objects become unreachable. You lose size, iteration, and clear(), so you can no longer list or count the stored requests.
Exercise
Why does new WeakSet().add("visited") throw, while new WeakSet().add({}) works?
Show answer
WeakSet members must be objects (or non-registered symbols). A string is a primitive that can always be recreated, so it can never become unreachable, and a weak entry for it would make no sense.