CKTIS / JavaScript
WeakSet: checking and adding members with has() and add()
Use `has()` to check whether a value belongs to a `WeakSet` and `add()` to insert it. Membership is based on identity, and the collection does not keep its members alive.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const seen = new WeakSet();
seen.has(value);
seen.add(value);WeakSet.prototype.has/add is shorthand for two instance methods, WeakSet.prototype.has and WeakSet.prototype.add. seen.has(value) returns true if the value is present and false otherwise. seen.add(value) inserts the value if absent and returns the same WeakSet instance. Adding it again creates no duplicate, and the return value lets you chain add() calls.
Membership tests identity, not contents: two references to the same object identify the same member, but two separate objects with identical properties do not. ECMAScript 2024 accepts objects (including functions) and non-registered symbols, such as those created with Symbol(). For a symbol from Symbol.for(), a number, a string, or null, has() returns false and add() throws TypeError. Both methods also throw TypeError if this is not a WeakSet instance, for example when a detached method is called without binding it to the instance.
Membership alone does not prevent a value from being garbage-collected. You cannot predict when it will be reclaimed. A WeakSet has no size and cannot be iterated. Use it to mark objects you have already processed when you do not need to list them later. Choose Set if you need iteration, a size, or members such as numbers and strings.
Symbol support can vary by runtime. If you rely on it, test add() with a value created by Symbol() in the target runtime; checking that WeakSet exists is not enough.
Examples
{
const seen = new WeakSet();
const item = { id: 1 };
const alias = item;
console.log(seen.has(item));
console.log(seen.add(item).add(item) === seen);
console.log(seen.has(alias));
console.log(seen.has({ id: 1 }));
console.log(seen.has(1));
try {
seen.add(1);
} catch (error) {
console.log(error.name);
}
}Result
false true true false false TypeError
The first `has()` returns `false`. The two `add()` calls can be chained because the method returns the same instance. `alias` refers to the inserted object; a new object with the same `id` does not match. For the number `1`, the lookup returns `false` and insertion throws the caught `TypeError`.
Related lessons
- JavaScript · Lesson 17 · Advanced · Version: 4
- JavaScript · Lesson 43 · Advanced · Version: 4
- JavaScript · Lesson 45 · Advanced · Version: 4
- JavaScript · Lesson 40 · Intermediate · Version: 3