Hint
Keys are weakly held — objects can be GC'd; no iteration, no size — use for private metadata
WeakMap/WeakSet hold weak references to their keys/entries. The garbage collector can collect the referenced object — the entry is automatically removed. Keys must be objects.
// WeakMap — per-object cache that doesn't prevent GC
const cache = new WeakMap();
function process(user) {
if (cache.has(user)) return cache.get(user); // cache hit
const result = expensiveCompute(user);
cache.set(user, result);
return result;
}
// When user object is GC'd → cache entry vanishes automatically
// No manual cleanup needed!
// WeakSet — track objects without preventing GC
const processing = new WeakSet();
async function handleOnce(obj) {
if (processing.has(obj)) return; // already running
processing.add(obj);
await doWork(obj);
processing.delete(obj);
}
// WeakMap for private class fields (pre-#private syntax)
const _private = new WeakMap();
class Secure {
constructor() { _private.set(this, { secret: 42 }); }
getSecret() { return _private.get(this).secret; }
}
Key limitation: No .size, no iteration, no .keys()/.values(). You can't see what's in them — only access by key.