Keys held weakly: WeakMap notes stick to the deposit boxes at Bayu’s counter, the Map’s ledger hangs on the wall. Let a box go, count the entries, try a text…
Why it matters
The safe way to attach data to an object or a DOM node without leaking memory: private metadata, a cache per object. A plain Map holds its keys for ever; a WeakMap does not. The price: no .size, and no looping over it.
The key idea
A WeakMap holds its keys weakly
Common mistakes
wm.set('id', 1) throws a TypeError The key must be an object (or a non-registered Symbol). A primitive is never "unreachable" in the same way, so it is refused from the start.
Code looks for wm.size or for…of wm and gets nothing There on purpose, because its entries can shrink at any time, so listing them is not certain. When you need to count or loop, use a plain Map.
Thinking a WeakMap entry vanishes the moment its reference is let go It becomes unreachable, and the engine drops it *later*, if ever, without any sign. Do not rely on the timing for app logic; all that is certain is that your program can no longer ask about it.
Try it in this playground
Try a text key: wm.set('id', 1) A WeakMap takes only objects or non-registered Symbols.
Look for wm.size or [...wm] No size, no looping.
Let go of a box with a note With no delete, its note becomes unreachable too.
Watch a Map keep a box that was let go The leak a WeakMap prevents.