JavaScript WeakMap/WeakSet Garbage Collection Fix
In this tutorial, you'll learn about JavaScript WeakMap/WeakSet Garbage Collection Fix. We cover key concepts, practical examples, and best practices.
The Problem
WeakMap and WeakSet hold weak references to their keys, meaning the garbage collector can remove entries when the key object is no longer referenced elsewhere. Developers expect them to behave like Map/Set and are surprised when entries disappear or when they cannot iterate over them.
Quick Fix
Step 1: WeakMap keys must be objects
// Wrong — primitive keys are not allowed
const cache = new WeakMap();
cache.set('key', 'value');
// TypeError: Invalid value used as weak map key
// Right — use objects as keys
const key = { id: 1 };
cache.set(key, 'value');
console.log(cache.get(key)); // 'value'
Step 2: WeakMap is not iterable
const cache = new WeakMap();
const obj = { data: 42 };
cache.set(obj, 'cached');
// Wrong — WeakMap has no size, forEach, or iteration
console.log(cache.size); // undefined
cache.forEach((v, k) => console.log(k)); // TypeError
// Right — manage keys yourself if iteration is needed
const trackedKeys = new Set();
trackedKeys.add(obj);
cache.set(obj, 'cached');
trackedKeys.forEach(key => {
console.log(cache.get(key));
});
Step 3: Garbage collection removes entries silently
let user = { name: 'Alice' };
const cache = new WeakMap();
cache.set(user, { lastLogin: '2026-06-24' });
// Remove the strong reference — WeakMap entry may be GC'd
user = null;
// The cached data may be collected on next GC cycle
// Cannot rely on cache.get() returning a value
Step 4: Use WeakSet for object collections without memory leaks
const visited = new WeakSet();
function processNode(node) {
// Wrong — Set would prevent GC of DOM nodes
// if (visitedSet.has(node)) return;
if (visited.has(node)) return; // Right
visited.add(node);
// Process node...
}
// When the DOM node is removed, the WeakSet entry is automatically GC'd
Prevention
- Only use WeakMap/WeakSet when keys are objects that need garbage collection
- Use Map/Set instead when you need iteration, size tracking, or primitive keys
- Do not rely on WeakMap entries persisting — they may be GC'd at any time
- Maintain a separate key registry if you need to enumerate WeakMap entries
- Use WeakMap for caching DOM nodes, private instance data, and listener registrations
Common Mistakes with weakmap gc
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro