Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Collections

The WeakSet object

Reference for JavaScript WeakSet: a set of weakly held objects with add(), has() and delete(). Learn why it cannot be iterated and when to use it for tagging.

A WeakSet stores objects (or non-registered symbols) without keeping them alive. Membership is all it tracks: an object is either in the set or it is not. When the last normal reference to an object goes away, the object can be garbage collected and it silently leaves the set.

A WeakSet is a good fit for marking objects, for example "this node has already been processed" or "this object has passed validation", without changing the objects themselves and without leaking memory.

JavaScript
const seen = new WeakSet();
const node = { id: 1 };

seen.add(node);
console.log(seen.has(node));

Try it

JS Tracking visited objects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
new WeakSet()
new WeakSet(iterable)

weakSet.add(value)
weakSet.has(value)
weakSet.delete(value)
Name Description
iterable Optional. An iterable of objects to add at construction time.
value An object, or a symbol that was not created with Symbol.for().

Return value: add() returns the WeakSet itself. has() returns a boolean. delete() returns true if the value was in the set and false otherwise.

Exceptions: add() and the constructor throw a TypeError for values that are not objects or non-registered symbols. has() and delete() return false for such values instead of throwing.

Usage notes

  • No iteration, no size, no clear(). The set's contents depend on garbage collection timing, so they cannot be listed. Use a Set when you need to enumerate.
  • Identity matters. Two separate objects with equal contents count as different members.
  • Adding twice is harmless. The second add() of the same object has no effect.
  • Typical uses: cycle detection in graphs (as above), flagging objects as initialized, brand checks for private data.
  • Compared with a Set: a Set keeps its members alive and can be iterated; a WeakSet does neither.
  • Compared with a boolean property: a WeakSet works on frozen objects and on objects you must not modify, and it leaves no trace on the object.

Browser support

WeakSet works in all current browsers. Symbols as members are more recent, so check a compatibility table if you need them.