JS WeakMap and WeakSet
In this page:
WeakMap Basics
WeakMap stores key-value pairs where keys must be objects. It does not prevent those keys from being garbage collected. Because WeakMap keys can still be garbage collected once nothing else references them, WeakMap avoids the memory leaks a regular Map would create if you forgot to clean up entries.
Example: WeakMap Basics
const wm = new WeakMap();
const obj = {};
wm.set(obj, "some data");
console.log(wm.get(obj));
WeakMap Object Keys
WeakMap keys must be objects. Strings, numbers, and other primitive values cannot be keys. This restriction is what enables the garbage-collection benefit: primitives are never garbage collected the way object references are, so allowing them as keys wouldn't make sense.
Example: WeakMap Object Keys
const wm = new WeakMap();
const key = {};
wm.set(key, "value");
// wm.set("string", "value"); // TypeError: Invalid value used as weak map key
console.log(wm.get(key));
WeakSet Basics
WeakSet stores objects. It is useful when you only need to know whether an object has been added. Unlike a regular Set, a WeakSet doesn't support iteration or a size property, trading those conveniences for the same automatic-cleanup benefit as WeakMap.
Example: WeakSet Basics
const ws = new WeakSet();
const obj = {};
ws.add(obj);
console.log(ws.has(obj));
WeakMap and Private Data
A WeakMap can keep data associated with objects without adding visible properties to those objects. This is a common pattern for simulating private class fields before native private fields existed, since outside code has no way to enumerate or access the WeakMap directly.
Example: WeakMap and Private Data
const privateData = new WeakMap();
class User {
constructor(name) {
privateData.set(this, { name });
}
getName() {
return privateData.get(this).name;
}
}
console.log(new User("Sam").getName());
When to Use Weak Collections
Use WeakMap or WeakSet when object lifetime matters and you do not need normal iteration over the collection. Reach for WeakMap/WeakSet when you're associating metadata with objects you don't own the lifetime of, and for plain Map/Set otherwise, since they support far more operations.
Example: When to Use Weak Collections
const visited = new WeakSet();
function markVisited(node) { visited.add(node); }
const el = {};
markVisited(el);
console.log(visited.has(el));
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: