WeakMap is a specialized Map whose keys must be objects and are held "weakly" — meaning they don't prevent garbage collection. It exists specifically to attach metadata to objects without causing memory leaks.
1WeakMap | JavaScript Tutorial - In-Depth Guide Part 1
A WeakMap holds its keys 'weakly' — if no other reference to a key object exists anywhere else in the program, it can be garbage collected, automatically removing that entry from the WeakMap too.
let obj = { id: 1 };
const wm = new WeakMap();
wm.set(obj, 'metadata');
obj = null; // the object can now be garbage collected,
// and its WeakMap entry disappears with itWeak References
2WeakMap | JavaScript Tutorial - In-Depth Guide Part 2
WeakMap keys must be objects (or, more recently, certain non-registered Symbols) — primitive values like strings or numbers are not allowed.
const wm = new WeakMap();
wm.set('key', 'value'); // TypeError: Invalid value used as weak map keyObject Keys Only
3WeakMap | JavaScript Tutorial - In-Depth Guide Part 3
WeakMap is not iterable and has no size property — since entries can vanish at any time via garbage collection, the language deliberately hides its contents from enumeration.
const wm = new WeakMap();
wm.size; // undefined — no such property
for (const x of wm) {} // TypeError: wm is not iterableNo Iteration, No size
4WeakMap | JavaScript Tutorial - In-Depth Guide Part 4
A classic use case is caching computed data per DOM element or object, without preventing that element from being garbage collected once it's removed from the page.
const layoutCache = new WeakMap();
function getLayout(el) {
if (!layoutCache.has(el)) {
layoutCache.set(el, computeExpensiveLayout(el));
}
return layoutCache.get(el);
}Memory-Safe Element Caching
5WeakMap | JavaScript Tutorial - In-Depth Guide Part 5
WeakMap is also a common technique for true private data on class instances, predating (and still sometimes preferred over) the '#' private field syntax.
const privateData = new WeakMap();
class BankAccount {
constructor(balance) {
privateData.set(this, { balance });
}
getBalance() {
return privateData.get(this).balance;
}
}Private Instance Data
6Step-by-Step Breakdown
A WeakMap holds its keys 'weakly' — if no other reference to a key object exists anywhere else in the program, it can be garbage collected, automatically removing that entry from the WeakMap too.
WeakMap keys must be objects (or, more recently, certain non-registered Symbols) — primitive values like strings or numbers are not allowed.
Checkpoint: Can a string be used as a WeakMap key?
- →Yes, any value type is allowed
- →No, WeakMap keys must be objects
WeakMap is not iterable and has no size property — since entries can vanish at any time via garbage collection, the language deliberately hides its contents from enumeration.
Checkpoint: Does WeakMap support iteration with for...of or a .size property?
- →Yes, just like a regular Map
- →No, both are intentionally unavailable
A classic use case is caching computed data per DOM element or object, without preventing that element from being garbage collected once it's removed from the page.
WeakMap is also a common technique for true private data on class instances, predating (and still sometimes preferred over) the '#' private field syntax.
Next, we'll explore 'WeakSet'.
Level Up 🚀
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1WeakMap Prevents Memory Bloat in Long-Lived Accessible Widget Trees
Caching per-element ARIA computation results in a WeakMap ensures that as accessible widgets are dynamically added and removed from a long-running single-page app, their cached metadata doesn't accumulate indefinitely in memory.
SEO Implications
- 1
No Direct SEO Effect
WeakMap is a memory-management tool; SEO relevance is limited to preventing memory leaks that could degrade long-session client-side performance.
Best Practices
Use WeakMap for Metadata Attached to Objects You Don't Own the Lifecycle Of
DOM elements, third-party objects, or any object whose removal you don't directly control are exactly the case where a regular Map would risk leaking memory, and WeakMap avoids that risk automatically.
Prefer Native `#` Private Fields for New Class-Based Code
The WeakMap-based private data pattern still works and is important to recognize in existing code, but for new class code the built-in `#` private field syntax is simpler and doesn't require a separate module-scoped WeakMap.
Frequent Bugs
Using a regular Map to cache data keyed by DOM elements that get created and destroyed frequently, causing steadily increasing memory usage as removed elements are never released.
Switch to WeakMap so entries for removed, no-longer-referenced elements are automatically eligible for garbage collection.
Trying to iterate a WeakMap or check its size to debug what's stored in it, and being confused when neither operation is available.
Remember WeakMap intentionally has no iteration or size introspection; if you need to enumerate cached items, track their keys separately in a regular array or Set alongside the WeakMap.
Real-World Examples
Attaching Event Listener Metadata to DOM Elements
A UI framework needed to associate cleanup functions with dynamically created DOM elements, ensuring the metadata didn't outlive the elements themselves once removed from the page.
const cleanupFns = new WeakMap();
function attachCleanup(el, fn) {
cleanupFns.set(el, fn);
}
function removeElement(el) {
cleanupFns.get(el)?.();
el.remove();
}