WeakSet in JavaScript
WeakSet is a "lightweight" version of Set that stores only objects and holds them by a weak reference, which is where the word Weak comes from. It is designed for situations where you want to keep unique objects around but must not prevent the garbage collector (GC) from removing them once they are no longer used anywhere else.
Theory
TL;DR
WeakSetstores objects only, primitives throw aTypeError.- References to its elements are weak: the GC may remove an object while it still sits in the collection.
- Only three methods exist:
add(value),delete(value),has(value). - There is no
size,forEach,keys,valuesorentries, because the collection cannot be iterated. - Elements are unique, exactly like in a
Set. - Typical uses: "already processed" marks, a temporary cache, private data.
Quick example
const ws = new WeakSet();
const obj1 = { name: 'Alice' };
const obj2 = { name: 'Bob' };
ws.add(obj1);
ws.add(obj2);
console.log(ws.has(obj1)); // trueWhat matters here:
-
The collection stores objects only, not primitives. Trying to add a string or a number fails immediately.
javascriptws.add(123); // TypeError: Invalid value used in weak set -
If
obj1is no longer used anywhere, the garbage collector removes it automatically and the entry disappears from theWeakSet.
WeakSet methods
| Method | Description | Example |
|---|---|---|
add(value) | adds an object | ws.add(obj) |
delete(value) | removes an object | ws.delete(obj) |
has(value) | checks for presence | ws.has(obj) |
Note that there are no size, forEach, keys, values or entries methods, because a WeakSet cannot be iterated. That is not a whim of the specification: the GC removes elements at an unpredictable moment, so any iteration would produce a non deterministic result.
The main difference from Set
| Property | Set | WeakSet |
|---|---|---|
| Can store primitives | Yes | No, objects only |
| Elements are weakly held (GC may remove them) | No | Yes |
Can be iterated (for...of, size) | Yes | No |
| Used for temporary references | Rarely | Often |
Automatic removal from memory
let obj = { id: 1 };
const ws = new WeakSet();
ws.add(obj);
console.log(ws.has(obj)); // true
obj = null; // the object is no longer reachable
// the object will be removed from memory automatically by the garbage collectorHow this works:
- After
obj = nullthe object is reachable only from theWeakSet, and such a reference does not count as a strong one, so the GC is free to remove it. - That is exactly what makes
WeakSetconvenient for holding temporary or cached objects: you never have to clean up by hand.
A practical example: tracking processed objects
const processed = new WeakSet();
function process(obj) {
if (processed.has(obj)) {
console.log('Already processed');
return;
}
processed.add(obj);
console.log('Processing:', obj.name);
}
const user = { name: 'Alice' };
process(user); // Processing: Alice
process(user); // Already processed
// after user = null the object disappears from the WeakSet automaticallyHere the WeakSet acts as an "invisible flag" on the object: we do not bolt a service field such as obj.__processed onto it, we do not pollute the data structure, and we do not keep the object alive longer than necessary.
In short
| Property | Value |
|---|---|
| Type | A collection of unique objects |
| Primitives | Not allowed |
| Garbage collector | May remove elements |
| Iteration | Impossible |
| Methods | add, delete, has |
| Common use | Caching, "processed" marks, private data |
Summary:
WeakSetis a collection of unique objects that are removed from memory automatically once no other references to them remain. It is excellent for temporary marks and caching, and a poor fit when data has to be stored permanently or iterated over.
Common mistakes
- Trying to add a primitive.
ws.add('text')orws.add(5)is aTypeError, only an object can be a member. - Looking for
sizeor a loop. Counting the elements or walking over them is impossible by design; use a regularSetfor that. - Storing long lived data in a
WeakSet. With no external references the entry may vanish at any time, this is not a storage. - Assuming removal is instant. The GC runs whenever it sees fit, so
has()is not guaranteed to returnfalseright after you drop the last reference. - Confusing it with
WeakMap. AWeakSetstores the objects themselves, aWeakMapstores "object to value" pairs. - Turning it into a result cache. A
WeakSetremembers only the fact of membership; to attach a value to an object you need aWeakMap.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.