Back to results for “Memory Management”
JavaScript › Memory Management & Garbage Collection

How does using WeakMap/WeakSet as a design choice actively prevent certain classes of memory leaks?

Advanced

Answer

Because WeakMap/WeakSet hold their object keys/values weakly, associating metadata with an object this way never by itself prevents that object from being garbage collected — unlike a regular Map or array, which would keep the object alive as long as the cache itself exists, even after nothing else references it.
// Regular Map: keeps 'el' alive forever, even after removal from DOM
const metaMap = new Map();
metaMap.set(el, { clicks: 0 });

// WeakMap: 'el' can still be GC'd once removed and unreferenced elsewhere
const metaWeakMap = new WeakMap();
metaWeakMap.set(el, { clicks: 0 });
Real-world example Choosing WeakMap specifically to attach UI state to DOM elements that may be dynamically added and removed many times.

Common follow-ups: Are there real performance trade-offs to using WeakMap over Map, beyond the GC behavior?