WeakMap, WeakSet & Garbage Collection
JS جاوااسکریپت

WeakMap, WeakSet & Garbage Collection

Understand weak references, private metadata, and how the GC interacts with your data structures.

BugCast Admin··۵ دقیقه مطالعه

WeakMap and WeakSet hold keys weakly so objects can be garbage-collected when nothing else references them. This is useful for caches and private data attached to DOM nodes.

Common Interview Questions

Q: Why can't WeakMap keys be primitives?

Answer: Weak references only make sense for objects. Primitives are not garbage-collected individually — they are values, not heap objects with identity.

Q: What happens when a WeakMap key is collected?

Answer: The corresponding entry disappears automatically. You cannot enumerate WeakMap, so you cannot observe removal directly — you simply won't find the key on next get.

Q: Give a practical WeakMap use case

Answer: Store per-instance private state without polluting the object or closing over closures in every method. When the instance is GC'd, metadata goes with it.


const privateData = new WeakMap();

class User {
  constructor(name) {
    privateData.set(this, { name });
  }
  getName() {
    return privateData.get(this).name;
  }
}

Q: WeakSet vs Set?

Answer: WeakSet only stores objects weakly and is not iterable. Use it to tag objects (e.g., visited nodes in a graph) without preventing GC.

Key Points for Interviews

  • Weak collections do not prevent garbage collection

  • No size, keys, or iteration on WeakMap/WeakSet

  • Ideal for DOM-node metadata and private fields (pre-# syntax)

  • Strong Map cache can cause memory leaks for short-lived objects

  • Modern #private fields reduce some WeakMap patterns in classes

#weakmap#gc#interview

مطالب مرتبط