Glossary / WeakSet

WeakSet

WeakSet tracks membership of objects without keeping them alive solely because they are members. It is useful for marking objects as processed or associating a temporary membership flag with an object’s lifetime. It is intentionally limited: it cannot be enumerated or counted, and it is not a general-purpose set for arbitrary values.

Membership semantics

const visited = new WeakSet();
function visit(node) {
  if (visited.has(node)) return;
  visited.add(node);
  // process node
}

Membership is by object identity. Two different objects with the same fields are distinct members. Primitive values such as strings and numbers cannot be added; supported non-registered Symbols are a recent capability, so check targets if using that edge case. WeakSet has add, has, and delete, but no size, iteration, or clear operation. Those omissions avoid exposing GC-dependent contents.

Use a regular Set when you need to enumerate, count, or clear membership, or when values are primitives. A WeakSet does not guarantee when memory is reclaimed and should not be used to trigger cleanup. For traversal algorithms, also consider whether the visited set should persist beyond one operation; a local ordinary Set may be clearer.

Interview questions

  1. What can a WeakSet contain? Objects and supported non-registered Symbols, not ordinary primitives.
  2. Can it be enumerated? No.
  3. How does it compare objects? By identity.
  4. When is Set the better choice? When size, iteration, clearing, or primitive members are needed.

References