JavaScript·Advanced·Coding·1 min read
Why do WeakMap keys not prevent collection?
Short interview answer
A WeakMap does not keep its object keys strongly reachable. When a key has no other strong path from a root, its entry may disappear. Weak collections are non-enumerable because collection timing cannot become observable.
Example
const meta = new WeakMap();let node = document.createElement('div');meta.set(node, { renderedAt: Date.now() });
node = null; // nothing else references the div -> // the div AND its WeakMap entry become collectibleKey takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.