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.
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.
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
What is the difference between a Map and a WeakMap, and why can't you iterate a WeakMap?
Give three real uses for WeakMap or WeakSet.
What does WeakRef.deref() return, and why shouldn't program logic depend on it?
Why must WeakMap keys be objects?
Preview
Console
Nothing logged yet.Expected console output
150
Account { owner: 'Asha' }
true
WeakMap {}
size: undefined
TypeError: Invalid value used as weak map key