JavaScript WeakMap: Object-associated Metadata
Quick answer
WeakMap associates values with eligible weak keys without keeping the key alive merely because it is in the map. It is useful for metadata tied to another object’s lifetime.
How it works
Objects and nonregistered symbols are eligible keys in the modern standard; registered symbols and other primitives are not. Use set, get, has, delete. There is no size or entry iterator because membership lifetime depends on garbage collection. Use objects for the local examples. The value may be any JavaScript value.
const key={}; const m=new WeakMap(); m.set(key,"draft"); console.log(m.get(key), m.has({}));Expected output in Node.js:
draft falseThe lookup uses the original object identity.
const k={}; const m=new WeakMap([[k,4]]); console.log(m.delete(k), m.has(k), typeof m.keys);Expected output in Node.js:
true false undefinedDeletion is explicit; WeakMap has no keys iterator.
Common mistakes
WeakMap is not a cache with a guaranteed eviction deadline. A new object with identical fields cannot access metadata for the original object.
Practice
Associate a display label with each object in a list; explain why ordinary string identifiers need Map instead.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript WeakMap: Object-associated Metadata — Knowledge Check
Apply the taught concept and predict the output.
Why does WeakMap lack an enumeration API?
Which key is a portable WeakMap choice?
Can WeakMap store a primitive as its associated value?
What is the exact console output in JavaScript WeakMap: Object-associated Metadata example 1?
const key={}; const m=new WeakMap(); m.set(key,"draft"); console.log(m.get(key), m.has({}));What is the exact console output in JavaScript WeakMap: Object-associated Metadata example 2?
const k={}; const m=new WeakMap([[k,4]]); console.log(m.delete(k), m.has(k), typeof m.keys);