Command Palette

Search for a command to run...

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

WeakMap for private data

The balance isn't a property of the object, so logging it doesn't show it. A WeakMap shows no contents and has no size.

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?

WeakMap for private data ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

150
Account { owner: 'Asha' }
true
WeakMap {}
size: undefined
TypeError: Invalid value used as weak map key