WeakMap and WeakSet
Learn how WeakMap and WeakSet work with the garbage collector.
What is a WeakMap?
A WeakMap is a Map variant whose keys must be objects. The held reference is weak: when an object is no longer used anywhere else, the garbage collector reclaims it and it disappears from the WeakMap automatically.
This is useful when you want to attach extra data to an object and have that data vanish once the object is gone. WeakMap has no size property and no keys()/values() methods; its contents cannot be listed.
WeakSet and its use
A WeakSet is a Set variant that holds objects weakly. You add an object, check with has, and remove it with delete. Duplicate objects are not stored.
A typical use is tracking whether an object is "marked". For example, you can use a WeakSet to remember whether a DOM element has already been registered with an event listener; once the element is removed, the entry cleans up automatically.
Exercise Attach metadata with WeakMap
Create a WeakMap called meta. Define an object called btn. Use meta.set(btn, ...) to attach { seen: true } to it. Log the result of meta.has(btn) with console.log.
Show example solution
const meta = new WeakMap();
const btn = { name: "Alex" };
meta.set(btn, { seen: true });
console.log(meta.has(btn));
Test yourself
-
Which is valid for WeakMap keys?
- Only string keys
- Number, string and object keys
- Only object keys
- Any type
Show answer
Only object keys — Correct. WeakMap keys must be objects.
-
Add a value to a WeakMap
const meta = new WeakMap(); const btn = {}; meta.____(btn, { count: 0 }); console.log(meta.has(btn));Show answer
const meta = new WeakMap(); const btn = {}; meta.set(btn, { count: 0 }); console.log(meta.has(btn)); -
WeakMap and WeakSet traits
- WeakMap key
- Only objects
- WeakSet item
- Only objects accepted
- size property
- Not available, not iterable
- garbage collector
- Cleans up automatically
-
Which statement about WeakMap is correct?
- contents cannot be listed; keys are objects
- size property returns the entry count
- keys() lists all keys
- entries can be iterated with for...of
Show answer
contents cannot be listed; keys are objects — Correct. WeakMap is not iterable; size is also missing.