Skip to the workspace
Pebellslearn by building
Data Structures  ›  Lesson

WeakMap and WeakSet

Weak Map 12 min

javascript / WeakMap and WeakSet

Explore each scene at your own pace.

01 · WeakMap and WeakSet

WeakMap and WeakSet

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

Walk through the modelWeakMap and WeakSetAuthored snapshots of the example; use Run below to test the code.
articleobject A
The application owns an ordinary strong reference.
1 of 3

Follow one example

javascript

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.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.