Sub topic 15
WeakSet Fundamentals and Object Tagging
This chapter assumes you already know the Set API, understand reachability and garbage collection, and know which values weak collections accept. It also assumes you know the difference between primitive values and object references. The focus here is the WeakSet API and the main thing it is used for: tagging objects. Tagging means recording a yes-or-no fact about an object without changing the object or keeping it alive.
What a WeakSet Is
A WeakSet is a collection of objects in which each object appears at most once. It works like a Set with one difference: it holds its members weakly. If nothing else in the program can reach a member, the garbage collector may reclaim that object, and it then leaves the WeakSet with no action from your code.
A WeakSet answers a single question: "Have I marked this exact object?" It stores no value alongside a member. When you need to attach data to an object, use a WeakMap. When a boolean flag is enough, a WeakSet is the simpler tool.
The API
The API has three instance methods and a constructor.
| Operation | Returns | Notes |
|---|---|---|
| `new WeakSet(iterable)` | a new WeakSet | Every item must be a valid weak value, or the constructor throws a `TypeError` |
| `ws.add(value)` | the WeakSet itself | Chainable. Adding an existing member does nothing |
| `ws.has(value)` | `true` or `false` | Never throws, even for primitives |
| `ws.delete(value)` | `true` if removed, else `false` | Never throws |
const a = { name: 'a' };
const b = { name: 'b' };
const marked = new WeakSet([a]);
marked.add(b).add(b); // chaining; the second add is a no-op
console.log(marked.has(a)); // true
console.log(marked.has(b)); // true
console.log(marked.delete(a)); // true
console.log(marked.delete(a)); // false (already gone)
console.log(marked.has(a)); // false
console.log(marked.has('a')); // false, no error for primitives
try {
marked.add(42);
} catch (err) {
console.log(err instanceof TypeError); // true
}has and delete accept any value and return false for anything that cannot be a member. add and the constructor are stricter. They throw on primitives, because they would otherwise have to store a value that can never be collected.
Missing on Purpose: size, clear, and Iteration
A WeakSet has no size, no clear(), no forEach, and no iterator. Earlier chapters gave the reason: membership depends on when the garbage collector runs, so counting or listing members would give results that differ from one run to the next. In practice, this means a WeakSet cannot answer "which objects have I marked?" It can only answer "is this object marked?" If you ever need the full list, the WeakSet is the wrong collection.
To reset a WeakSet, replace it with a new one:
let seen = new WeakSet();
// ... use it ...
seen = new WeakSet(); // the old one and its entries become collectableTagging by Identity
Tagging works by identity. Two objects with identical contents are still two separate members, and a copy of a tagged object is not tagged.
const processed = new WeakSet();
const config = Object.freeze({ id: 7 });
processed.add(config); // works on frozen objects
console.log(processed.has(config)); // true
console.log(processed.has({ ...config })); // false: a copy is a new object
console.log(Object.isFrozen(config)); // true: the object was not modifiedThe frozen object shows why tagging from the outside is useful. Setting a property such as config.processed = true fails on a frozen object: it is silently ignored in sloppy mode and throws in strict mode. A tag property would also show up in Object.keys, in JSON.stringify output, and in for-in loops. It could even collide with a property some other library uses. A WeakSet keeps the mark outside the object, so none of these problems apply.
Pattern: Do Something Only Once per Object
A common use is to guard work that must happen exactly once for each object, such as handling an event or initializing a DOM node. The guard set does not stop handled objects from being collected later.
const handled = new WeakSet();
function handleOnce(event) {
if (handled.has(event)) return false;
handled.add(event);
console.log('handling', event.type);
return true;
}
const click = { type: 'click' };
console.log(handleOnce(click)); // logs 'handling click', then true
console.log(handleOnce(click)); // falseA Set would work for this just as well while the program runs. Over time, though, it would hold on to every event the program ever handled, which is a memory leak. The WeakSet version never holds an event longer than the rest of the program does.
Pattern: Detecting Cycles Correctly
Traversals use a WeakSet to avoid looping forever on circular structures. Watch for one edge case here. A visited set is not the same thing as a set of objects on the current path. An object referenced from two places is shared, but that does not make the structure circular. To detect real cycles, add each object when you enter it and remove it when you leave.
function hasCycle(value, path = new WeakSet()) {
if (value === null || typeof value !== 'object') return false;
if (path.has(value)) return true;
path.add(value);
for (const child of Object.values(value)) {
if (hasCycle(child, path)) return true;
}
path.delete(value);
return false;
}
const shared = { n: 1 };
console.log(hasCycle({ a: shared, b: shared })); // false: shared, not circular
const loop = { name: 'loop' };
loop.self = loop;
console.log(hasCycle(loop)); // trueIf you remove the path.delete(value) line, the function reports the shared object as a cycle. A "visited" set without deletes fits a different job: skipping work you have already done, as the walk function did in an earlier chapter.
Pattern: Brand Checks
A brand check confirms that an object was created by your constructor. It does not settle for an object that merely looks like one. Checking instanceof is not enough, because anyone can build an object with the same prototype using Object.create(Token.prototype). A module-scoped WeakSet is a record that only your constructor can write to.
const tokens = new WeakSet();
class Token {
constructor(value) {
this.value = value;
tokens.add(this);
}
static isToken(obj) {
return tokens.has(obj);
}
describe() {
if (!tokens.has(this)) throw new TypeError('Not a Token');
return `Token(${this.value})`;
}
}
const real = new Token('abc');
const fake = Object.create(Token.prototype);
fake.value = 'abc';
console.log(fake instanceof Token); // true: instanceof is fooled
console.log(Token.isToken(real)); // true
console.log(Token.isToken(fake)); // false
try {
fake.describe();
} catch (err) {
console.log(err.message); // 'Not a Token'
}In modern classes, a private field and #field in obj do the same job with built-in syntax. The WeakSet approach is still useful in three cases: when you write plain functions instead of classes, when several classes or factories share one brand, or when you need to brand objects you did not create, such as objects you have already validated.
Set or WeakSet?
| Need | Use |
|---|---|
| Members are primitives | `Set` |
| You need to count, list, or iterate members | `Set` |
| You only ask "is this object marked?" | `WeakSet` |
| Marks should not keep objects alive | `WeakSet` |
| The marking code lives briefly and you need the members afterward | `Set` |
Exercise
A logging library calls markLogged(obj) on every object it logs and later asks "how many distinct objects have been logged?" The author stores the marks in a WeakSet. What is wrong with this design, and what should change?
Show answer
A WeakSet has no size and cannot be iterated, so the count cannot be computed. A count would also be nondeterministic even if the API allowed it, because collected objects drop out at unpredictable times. Keep the WeakSet for the "already logged?" check and add a separate numeric counter that you increment the first time each object is marked, that is, when has returns false before add.
Exercise
In the hasCycle function, what does hasCycle({ a: shared, b: shared }) return if you delete the line path.delete(value), and why?
Show answer
It returns true. Without the delete, shared stays in the WeakSet after the traversal of a finishes. When the traversal reaches b, it finds shared already marked and reports a cycle, even though the structure has no cycle. The set then records every object visited, not the current path.
Exercise
Which of these calls throw a TypeError on an ES2023 engine: ws.add(Symbol('x')), ws.add(Symbol.for('x')), ws.has(5), new WeakSet([{}, 'a'])?
Show answer
ws.add(Symbol.for('x')) throws because registered symbols are never collectable. new WeakSet([{}, 'a']) throws because the string 'a' is a primitive. ws.add(Symbol('x')) succeeds, and ws.has(5) returns false without throwing.