Non-retaining object tagging
Track whether objects have already been processed without extending their lifetime.
JavaScript · Class
WeakSet is a collection of unique objects and non-registered symbols held weakly, so unreachable members may be garbage-collected. It supports membership checks and mutation but cannot be enumerated.
WeakSet stores unique objects and non-registered symbols through weak references. It supports adding, checking, and deleting individual values, while intentionally providing no enumeration mechanism, so values can become garbage-collectable when nothing else strongly references them.
new WeakSet()
new WeakSet(iterable)| Name | Type | Description |
|---|---|---|
iterable | Iterable | Optional iterable whose elements are added to the new WeakSet. Each element must be an object or a non-registered symbol; null is treated as undefined. |
A newly created WeakSet object.
const seen = new WeakSet();
const first = { id: 1 };
const second = { id: 1 };
seen.add(first);
console.log(seen.has(first)); // true
console.log(seen.has(second)); // false
seen.delete(first);
console.log(seen.has(first)); // falseThe set tracks the first object by identity; a separate object with identical contents is not the same value.
Track whether objects have already been processed without extending their lifetime.
Associate temporary membership with objects in caches or lifecycle-sensitive workflows.
Prevent repeated handling of object references during graph or tree traversal.
WeakSet is useful when membership should not keep an object alive. Its references are weak, so an object may be garbage-collected when no other strong references remain.
Follow-up: How can code detect when an unreferenced member has been collected? It cannot observe that directly, because WeakSet deliberately has no enumeration or size mechanism.
WeakSet accepts objects and non-registered symbols, stores each value at most once, and compares objects by identity rather than by their contents.
Follow-up: What happens with two separately created objects containing the same properties? They are distinct references, so both can be members.
The main instance operations are add(), has(), and delete(). add() returns the WeakSet, has() returns a boolean, and delete() removes a matching value.
Follow-up: What does has() return for a primitive or registered symbol? It returns false rather than treating that value as a valid member.
SetWeakMapWeakRefWeakSet.prototype.add()WeakSet.prototype.delete()WeakSet.prototype.has()