JavaScript WeakSet: Weak Membership Tracking
Quick answer
WeakSet records membership of eligible weakly held values without imposing strong ownership. It is suited to membership checks on objects you already have.
How it works
Use add, has, delete on objects (or eligible nonregistered symbols in supporting runtimes). A WeakSet has no size, iterator or clear method. Ordinary Set is the right choice if you need to enumerate all members or use strings. WeakSet is useful for recording visited object identities while avoiding permanent ownership of those objects.
const x={}; const s=new WeakSet(); s.add(x); console.log(s.has(x),s.has({}));Expected output in Node.js:
true falseOnly x is registered.
const x={}; const s=new WeakSet([x]); console.log(s.delete(x), s.delete(x), typeof s.size);Expected output in Node.js:
true false undefinedOnly the first deletion removes a member; no size exists.
Common mistakes
Do not test whether an unreachable object has been collected. You cannot ask a WeakSet to list objects you no longer hold.
Practice
Explain how to record which UI model objects have been initialized without maintaining an enumerable registry.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript WeakSet: Weak Membership Tracking — Knowledge Check
Apply the taught concept and predict the output.
Which action is directly supported by WeakSet?
What should be used for a set of unique string tags?
What does weak membership guarantee about cleanup time?
What is the exact console output in JavaScript WeakSet: Weak Membership Tracking example 1?
const x={}; const s=new WeakSet(); s.add(x); console.log(s.has(x),s.has({}));What is the exact console output in JavaScript WeakSet: Weak Membership Tracking example 2?
const x={}; const s=new WeakSet([x]); console.log(s.delete(x), s.delete(x), typeof s.size);