WeakMap and WeakSet: keys that can be collected
A Map holds its keys strongly: as long as the map itself is reachable, every key in it is reachable too, and the garbage collector may not take them away. That is the right behaviour for a cache of values and the wrong one for data about objects that the program makes and drops all day, because the map grows and the memory with it. WeakMap and WeakSet hold their keys weakly.
This lesson shows the leak a strong map causes, the four methods a weak map has, and the two the language does not give it: there is no size and no iteration, because either one would tell a program which keys are still alive, and that answer depends on when the collector runs. The last section is the everyday use, private data attached to an object of JavaScript from the outside.
Why a weak map
The program below remembers something about three objects in a Map and then forgets the objects themselves. The map still holds them, so the size stays at three, and nothing in the program can remove them once the loop has finished. A weak map would let each entry go with its key, and its size would never be readable at all.
const cache = new Map();
function remember(key, value) {
cache.set(key, value);
}
for (let index = 0; index < 3; index += 1) {
remember({ id: index }, index * 10);
}
console.log('the cache holds:', cache.size);
console.log('and keeps every key alive:', [...cache.values()].join(','));
const weak = new WeakMap();
console.log('a WeakMap has no size:', typeof weak.size);
console.log('and no keys:', typeof weak.keys);
node leak.js
the cache holds: 3
and keeps every key alive: 0,10,20
a WeakMap has no size: undefined
and no keys: undefined
Three objects were made inside the loop, used as keys and lost: no name in the program refers to them any more. The strong map still counts three, because it is a reference like any other, and the values are still readable through it. The last two lines are the other half of the design: the weak versions drop the methods whose answer would depend on a collection that can happen at any moment, so there is nothing to ask about the whole map.
What a WeakMap can do
A WeakMap has four methods: set, get, has and delete. The key has to be an object or a function, and a primitive key throws a TypeError, because a number or a string is not something the collector can take away. The program does every call once.
const metadata = new WeakMap();
const ada = { name: 'ada' };
metadata.set(ada, { role: 'admin' });
console.log('get:', metadata.get(ada).role);
console.log('has:', metadata.has(ada), metadata.has({ name: 'ada' }));
console.log('delete:', metadata.delete(ada), metadata.has(ada));
try {
metadata.set('ada', 1);
} catch (error) {
console.log(error.name + ': ' + error.message);
}
console.log('the size is undefined:', metadata.size);
console.log('no iterator:', typeof metadata[Symbol.iterator]);
node api.js
get: admin
has: true false
delete: true false
TypeError: Invalid value used as weak map key
the size is undefined: undefined
no iterator: undefined
The calls behave as they do on a Map, and the look-alike object is again a different key. The TypeError is the rule in one line: only a value the collector can reclaim may be a weak key, so an object or a function and nothing else. The last two lines are what a weak map does not have, and they are why the output of a program that uses one is stable: no line of the output can depend on when a collection happened.
WeakSet as a mark
A WeakSet is the same idea for a set: add, has and delete, no size and no iteration. It answers one question about an object, whether it has been marked, and it forgets the mark when the object is gone. The program marks one of two look-alike objects.
const visited = new WeakSet();
const page = { url: '/dev/javascript/' };
const other = { url: '/dev/javascript/' };
console.log('before:', visited.has(page));
visited.add(page);
console.log('after:', visited.has(page), visited.has(other));
console.log('a look-alike was never visited:', visited.has({ url: '/dev/javascript/' }));
visited.delete(page);
console.log('after delete:', visited.has(page));
console.log('no size:', visited.size);
console.log('no iterator:', typeof visited[Symbol.iterator]);
node weakset.js
before: false
after: true false
a look-alike was never visited: false
after delete: false
no size: undefined
no iterator: undefined
The mark belongs to the object and not to its fields, so the second object with the same URL is untouched, and a fresh object written in the call is a third one. The delete removed the mark before the object ever went out of scope, which is the manual half of the lifetime. The two undefined lines are the difference from a Set: the collection cannot be counted or walked, and a program that needs either of those wants the strong version.
Data that belongs to an object
The usual use is a value that belongs to an object without being a field of it: an id, a cache, a lock. The weak map keeps the association outside the object, so the object stays the shape it was when it was made, and the entry disappears with it. The program gives an id to each object the first time it is asked.
const ids = new WeakMap();
let nextId = 1;
function idOf(object) {
if (!ids.has(object)) {
ids.set(object, nextId);
nextId += 1;
}
return ids.get(object);
}
const first = { name: 'ada' };
const second = { name: 'alan' };
console.log('first:', idOf(first));
console.log('the same object again:', idOf(first));
console.log('second:', idOf(second));
console.log('the object has no such field:', JSON.stringify(first));
node private.js
first: 1
the same object again: 1
second: 2
the object has no such field: {"name":"ada"}
The second call found the id that the first one stored, because the key is the same object, and the second object got its own. The last line is the point of the pattern: the record that goes to JSON, to a log or over the network has only its own fields, and the id stays in the map. A memoized function of objects can use the same structure for its results and does not have to hold its arguments forever.
Exercises
- Add a fifth round to the loop in leak.js. What does the size of the strong map say, and why can the weak version not report the same number?
- Store undefined under an object key in api.js and read it back with has. Which method tells the entry apart from a missing key?
- Call visited.add("text") in weakset.js. Which error comes out and what does the message name as the wrong value?
- Give a third object an id in private.js after the second one. Which number does it get, and which line of the output would change if the counter started at 100?
- Replace the WeakMap in private.js with a Map and print its size after the objects are gone. Which line shows the difference, and which method of the Map has no version on a WeakMap?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What kind of key does a WeakMap accept?
Answer
An object or a function, and nothing else
Only a value the garbage collector can reclaim may be a weak key, so a primitive throws a TypeError.
-
What does this program print?
const w = new WeakMap(); console.log(typeof w.size, typeof w.delete);Answer
undefined function
A WeakMap has delete like a Map and no size at all, because a size would depend on the collector.
-
What does this program print?
const w = new WeakMap(); try { w.set("key", 1); } catch (error) { console.log(error.message); }Answer
Invalid value used as weak map key
A string is not a value the collector can reclaim, so the call throws a TypeError with that message.
-
Can a WeakMap be walked with
for...of?Answer
No, it has no iterator at all
Iteration would show which keys are still alive, and that depends on the collector.
-
What is the difference between a Map and a WeakMap for its keys?
Answer
A Map keeps its keys alive, and a WeakMap lets them be collected
The strength of the reference is the whole difference, and it decides whether an entry outlives its key.
-
What does this program print?
const w = new WeakMap(); const k = { id: 1 }; w.set(k, "v"); console.log(w.get(k), w.get({ id: 1 }));Answer
v undefined
The second object is a different key, so only the first lookup finds the value.
-
What does this program print?
const s = new WeakSet(); const a = { id: 1 }; s.add(a); console.log(s.has(a), s.has({ id: 1 }));Answer
true false
A weak set compares identity, and the object in the second call was never added.
-
Why is a WeakMap a good place for an id that belongs to an object?
Answer
The id stays out of the object and its entry goes when the object is gone
The object keeps its own shape, and the association is not a reason for the object to stay in memory.
-
Which collection can be counted and printed in a stable way?
Answer
Map and Set
The weak collections have no size and no iteration, so their contents cannot be reported.
-
What happens to an entry of a WeakMap when its key becomes unreachable?
Answer
The entry may be removed with the key, and no code has to do it
That is what a weak reference means, and it is why the collection has no size to report.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev