WeakMap and WeakSet

Difficulty: Intermediate

Question

What are WeakMap and WeakSet in JavaScript, and how do they differ from Map and Set in terms of keys, iteration and garbage collection?

Answer

WeakMap is a key-value collection whose keys must be objects (or non-registered symbols since ES2023), and it holds those keys weakly: if nothing else in the program references a key, the garbage collector can reclaim it and the entry disappears. WeakSet is the same idea for a set of objects. Because entries can vanish at any time, neither collection is iterable and neither has a size, which is the main practical difference from Map and Set.

What "held weakly" actually means

A normal Map keeps a strong reference to every key. If you use a DOM node as a key and later remove the node from the page, the Map still keeps it alive, so the node and everything it points to leaks until you call delete.

A WeakMap does not count as a reference for garbage collection purposes. Once the last strong reference to the key object is gone, the key, and the value associated with it, become eligible for collection. The value is held strongly only as long as the key is alive. This structure is called an ephemeron.

Map vs WeakMap and Set vs WeakSet

FeatureMap / SetWeakMap / WeakSet
Key typesAny value, including primitivesObjects and non-registered symbols only
Reference to keyStrongWeak
Iteration (for...of, keys(), forEach)YesNo
size and clear()YesNo
Methodsget, set, has, delete, and moreget, set, has, delete (WeakSet: add, has, delete)
Typical useGeneral lookup tables, caches you controlMetadata attached to objects you do not own

The lack of iteration is deliberate. If you could list the keys, the result would depend on when the garbage collector last ran, which would make programs non-deterministic.

Where they are used in real code

Common mistakes

Map vs WeakMap during garbage collection. Switch the holder between Map and WeakMap under Tweak and run the collector.
  1. Roots: The collector starts from variables in scope, globals and active timers.
  2. Map keys are strong: A Map entry keeps its key object alive: a leak if never deleted.
  3. WeakMap keys are weak: They don't count for reachability, so the object is collected.
  4. Entry disappears: When the key object is collected, its WeakMap entry goes with it.

Code examples

Private per-instance state with WeakMap

const privateState = new WeakMap();

class Wallet {
  constructor(ownerId) {
    privateState.set(this, { ownerId, balanceInPaise: 0 });
  }
  deposit(paise) {
    privateState.get(this).balanceInPaise += paise;
  }
  get balance() {
    return privateState.get(this).balanceInPaise / 100;
  }
}

const w = new Wallet('user_42');
w.deposit(25050);
console.log(w.balance);
console.log(Object.keys(w));
// When `w` becomes unreachable, its WeakMap entry can be collected too.

The state is invisible on the instance and is tied to the instance's lifetime. This is the pattern compilers use to downlevel #private fields.

Weak tracking for a cycle-safe deep clone

function deepClone(value, seen = new WeakMap()) {
  if (value === null || typeof value !== 'object') return value;
  if (seen.has(value)) return seen.get(value); // cycle: reuse clone

  const copy = Array.isArray(value) ? [] : {};
  seen.set(value, copy);
  for (const key of Object.keys(value)) {
    copy[key] = deepClone(value[key], seen);
  }
  return copy;
}

const user = { name: 'Asha' };
user.self = user; // circular reference

const clone = deepClone(user);
console.log(clone.self === clone);
console.log(clone === user);

A WeakMap remembers which objects have already been cloned, so circular references map to the same copy instead of recursing forever. When the clone call finishes, the tracking map holds nothing alive.

Key points

Common follow-up questions

Interview tips

Concepts covered

WeakMap, WeakSet, Garbage Collection, Weak References, Memory Management

More JavaScript Interview questions