What is a WeakMap and WeakSet?
Weak collections hold references that don't prevent garbage collection, helping avoid memory leaks.
WeakMap — keys must be objects and are held weakly; if a key is no longer referenced elsewhere, it's collected and removed automatically.
WeakSet — stores objects weakly, with no duplicates.
Limitations — not iterable and no size, because contents can vanish at any time.
Use for attaching private data or metadata to objects without keeping them alive in memory.
// WeakMap — private data per object
const privateData = new WeakMap();
class User {
constructor(name, password) {
this.name = name;
privateData.set(this, { password }); // Truly private!
}
checkPassword(pw) {
return privateData.get(this).password === pw;
}
}
let user = new User('John', 'secret');
console.log(user.checkPassword('secret')); // true
// console.log(user.password); // undefined — private!
user = null; // User object garbage collected
// privateData entry is also cleaned up automatically!
// WeakSet — tracking without memory leaks
const visited = new WeakSet();
function processNode(node) {
if (visited.has(node)) return; // Already processed
visited.add(node);
// Process node...
}
// When node is removed from DOM, WeakSet entry is cleaned upWeakMap stores private password data keyed by the User instance. When the user is garbage collected, the WeakMap entry is automatically removed (no memory leak).
WeakSet tracks visited DOM nodes — when nodes are removed, the WeakSet entries are cleaned up. Neither needs manual cleanup.
The key insight: weak references do not prevent garbage collection. Use for associating data with objects without causing memory leaks.
The private data pattern (WeakMap keyed by this) is the most practical example. Know that keys must be objects and WeakMap/WeakSet are not iterable.