Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.4 — WeakMap, WeakSet and WeakRef
JavaScript · Example 3 of 3 ES2021+

WeakRef: deref() within one run

The engine keeps a WeakRef's target alive until the current job ends, so these lines are predictable. After that, deref() may return undefined at any later time, or never; that part can't be shown with a fixed output.

WeakMap and WeakSet hold objects without keeping them alive: when nothing else uses a key object, the garbage collector may remove it and its entry. WeakRef points at an object without keeping it alive. They exist for private data, caches and tagging objects you don't own.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write memoByObject(fn) that returns a function caching fn(obj) results in a WeakMap keyed by obj. Show that the second call with the same object doesn't call fn.

02

Write once(el, setup) that runs setup(el) only the first time it's called for a given element, using a WeakSet.

Explain it without notes

01

What is the difference between a Map and a WeakMap, and why can't you iterate a WeakMap?

02

Give three real uses for WeakMap or WeakSet.

03

What does WeakRef.deref() return, and why shouldn't program logic depend on it?

04

Why must WeakMap keys be objects?

WeakRef: deref() within one run ES2021+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

true
big data
still here in this run: true
function