WeakMap and WeakSet
WeakMap and WeakSet can associate data with collectible keys or members without acting like a strong enumerable registry. Their contents cannot be listed or counted reliably.
Use a weak association when owning the association should not by itself keep the key alive.
See the mechanism
object AFollow one example
The weak association does not provide a way to enumerate every key or read a size. This example uses object keys, the common case; modern JavaScript also permits certain nonregistered symbols. Clearing article removes that local strong reference, but you cannot then query the old key without retaining it elsewhere, and you cannot demand when collection occurs. Use Map when you need a list or count.
Predict, change and check
Predict: Could adding a parallel ordinary array of all keys accidentally keep the same objects alive?
Test your explanation: Compare the reference paths with and without such an array. Do not write a test that expects a key to disappear immediately after a timer.
The tasks below ask you to explain that result and apply the idea to different inputs.
Apply and distinguish
Weak association is not predictable collection
WeakMap and WeakSet support object keys and eligible non-registered symbols in modern implementations. This course's main example uses objects. Ordinary strings, numbers and registered Symbol.for symbols are not interchangeable weak keys. Check target-runtime support before adopting less widely supported cases.
Weak collections do not expose a size or a list of all keys. Keeping a separate array of every object key can reintroduce a strong retention path and defeat the intended lifetime behavior. Test explicit ownership and cleanup, not the exact time at which a garbage collector happens to reclaim a value.
Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.