WeakSet
A Set variant that holds weak references to objects, allowing entries to be garbage-collected when no other references exist.
Syntax
const ws = new WeakSet([iterable]); Parameters
| Name | Type | Required | Description |
|---|---|---|---|
iterable | Iterable<object> | null | No | An optional iterable of objects to pre-populate the set. Only objects and non-registered symbols are valid members. |
Returns
WeakSet — A new WeakSet instance.
Throws
TypeError— When a primitive value is passed to add().
Examples
// Cycle detection in a linked list traversal
function hasCycle(head) {
const seen = new WeakSet();
let cur = head;
while (cur) {
if (seen.has(cur)) return true;
seen.add(cur);
cur = cur.next;
}
return false;
}
const a = { val: 1, next: null };
const b = { val: 2, next: null };
a.next = b; b.next = a; // cycle
console.log(hasCycle(a));
Output
true
// Track processed DOM nodes without leaking memory
const processed = new WeakSet();
function process(node) {
if (processed.has(node)) return;
processed.add(node);
// ... do work
console.log('processed', node.id);
}
process({ id: 'btn-1' });
process({ id: 'btn-1' }); // different object reference — processes again
Output
processed btn-1
processed btn-1
Notes
Like WeakMap, WeakSet is not enumerable — it has no `size`, `keys()`,
`values()`, `entries()`, or `forEach()`. Its only methods are
`add(obj)`, `has(obj)`, and `delete(obj)`.
A WeakSet is appropriate when you need a "visited" or "seen" flag
on objects without preventing those objects from being GC-collected
when they go out of scope in the rest of the program.