WeakSet
A WeakSet is a set of objects held weakly. Membership does not keep the object alive, and you cannot iterate the set.
Detailed Explanation
WeakSet is to Set what WeakMap is to Map. You add objects, you has them, you delete them. You cannot walk the contents, you cannot ask size, and you cannot add a string or number. When the object is no longer reachable from anywhere else, the engine may drop it from the set.
The use is a tag. You want to mark objects you have already processed, or objects that should skip a second pass, without becoming the thing that keeps them in memory.
const seen = new WeakSet();
function visit(node) {
if (seen.has(node)) return;
seen.add(node);
walk(node);
}
If node is a DOM element that later disappears, seen will not retain the element. The same walk with a Set would keep every node until you clear the set.
WeakSets do not store values alongside the object. If you need data, use a WeakMap. If you need to list who is in the collection, use a Set and accept the strong references, or keep a separate array you manage yourself.
Non-object values throw. weak.add(1) is a TypeError. Registered symbols were not valid keys historically; follow the current engine if you need symbol members — objects are the intended case.
What it costs you: the same opacity as WeakMap. Debugging means you already have the object in hand and you ask has. You cannot log "everything we have seen". Tests cannot assert that a collected object vanished without controlling GC.
Reach for WeakSet when the only question is "have I tagged this object?" and you must not extend its lifetime. Reach for Set when members are primitives or you need to enumerate. Reach for a boolean property on the object when you own the object and a visible flag is fine.
Code Examples
const seen = new WeakSet();
const user = { id: 7 };
console.log(seen.has(user)); // => false
seen.add(user);
console.log(seen.has(user)); // => true
seen.delete(user);
console.log(seen.has(user)); // => falseconst locked = new WeakSet();
function lock(resource) {
if (locked.has(resource)) {
throw new Error("already locked");
}
locked.add(resource);
}
const file = { path: "/tmp/a" };
lock(file);
try {
lock(file);
} catch (err) {
console.log(err.message); // => already locked
}try {
new WeakSet().add("flag");
} catch (err) {
console.log(err.name); // => TypeError
}Common Gotchas
Only objects (and, in current engines, some symbols) can be members
primitives throw. Use `Set` for strings and numbers.
No iteration, no `size`
a WeakSet cannot answer "how many?" or "which?".
`add` of an object already present is a no-op
like `Set`, uniqueness is by reference.
Collection is not a reliable event
do not `await` the object disappearing from the WeakSet.