Skip to content

JavaScript WeakMap/WeakSet Garbage Collection Fix

DodaTech Updated 2026-06-24 3 min read

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

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. 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

### When should I use WeakMap instead of Map?

Use WeakMap when the keys are DOM nodes or other objects that should be garbage collected when no longer referenced. Use Map for all other cases where you need key-value storage with primitive keys or iteration.

How do I know if a WeakMap entry was garbage collected?

You cannot detect this directly. Call get() — if it returns undefined, the key was either never set or was collected. There is no way to distinguish between these cases.

Does WeakSet prevent the garbage collector from running?

No. WeakSet holds weak references, not strong ones. The GC can collect entries at any time. This is the entire purpose — preventing memory leaks from object references that should be transient.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro