CKTIS / JavaScript
WeakSet — a set with weak references
WeakSet holds unique objects and non-registered symbols without keeping them alive solely through membership. It provides add, has, and delete, but does not let you iterate over its elements or read their count.
Version: WeakSet was introduced in ECMAScript 2015 (ES2015). Support for non-registered symbols as elements was added in ECMAScript 2023 (ES2023).
Syntax
new WeakSet()
new WeakSet(iterable)
weakSet.add(value)
weakSet.has(value)
weakSet.delete(value)WeakSet tracks values, such as objects that have already been processed. Objects are distinguished by identity, not contents: two separate { id: 1 } objects are different elements. new WeakSet(iterable) adds values from the supplied iterable; the constructor requires new.
WeakSet.prototype.add(value) adds an element, ignores duplicates, and returns the same set, allowing chained calls. WeakSet.prototype.has(value) returns membership as a boolean. WeakSet.prototype.delete(value) returns true if it removed an existing element, or false otherwise.
Allowed values are objects, including functions, and symbols not registered through Symbol.for. For unsupported values, such as numbers, strings, null, or a result of Symbol.for, add throws TypeError, whereas has and delete return false. Symbol support was added in ECMAScript 2023; older engines may accept only objects. The language specification is not a browser compatibility table: check support for this feature in your target environment.
Unlike Set, WeakSet does not keep elements alive solely through membership. Garbage collection has no guaranteed timing. There is no size, iteration, forEach, or clear; checking membership requires holding the value being checked. Choose Set if you need to enumerate elements or know their count.
Examples
const first = { id: 1 };
const second = { id: 1 };
const seen = new WeakSet([first]);
console.log(seen.has(first));
console.log(seen.has(second));
console.log(seen.add(second) === seen);
console.log(seen.has(second));
console.log(seen.delete(first));
console.log(seen.delete(first));
console.log(seen.has(first));Result
true false true true true false false
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.
Sources
- ECMAScript® Language Specification
- ECMAScript® Language Specification — Keyed Collections
- ECMAScript® 2023 Language Specification — Keyed Collections
- ECMAScript® 2026 Language Specification — Executable Code and Execution Contexts
- Official reference — developer.mozilla.org: WeakSet / has
- Official reference — developer.mozilla.org: WeakSet / add
- Official reference — tc39.es: ecma262