What is WeakSet?
WeakSet is a "lightweight" version of Set,
which stores only objects and does so via a weak reference (hence the name Weak).
It is meant for situations where you want to store unique objects but not stop the garbage collector (GC) from removing them once they are no longer used anywhere else.
Creating a WeakSet
const ws = new WeakSet();
const obj1 = { name: "Alice" };
const obj2 = { name: "Bob" };
ws.add(obj1);
ws.add(obj2);
console.log(ws.has(obj1)); // true-
Stores only objects, not primitives. (Try adding a string or a number and you get an error.)
javascriptws.add(123); // TypeError -
If
obj1is no longer used anywhere else, the garbage collector removes it automatically from the WeakSet.
WeakSet methods
| Method | Description | Example |
|---|---|---|
add(value) | adds an object | ws.add(obj) |
delete(value) | removes an object | ws.delete(obj) |
has(value) | checks presence | ws.has(obj) |
No size, forEach, keys, values, entries methods
- because
WeakSetcannot be iterated.
Main difference from Set:
| Property | Set | WeakSet |
|---|---|---|
| Can store primitives | Yes | No (objects only) |
| Elements are "weakly held" (GC can remove them) | No | Yes |
Can be iterated (for...of, size) | Yes | No |
| Used for temporary references | Rarely | Often |
Example: automatic removal
let obj = { id: 1 };
const ws = new WeakSet();
ws.add(obj);
console.log(ws.has(obj)); // true
obj = null; // now the object is no longer reachable
// the object will automatically be removed from memory by the garbage collector- After
obj = nullthe object becomes reachable only from the WeakSet, so the GC (garbage collector) can remove it. - This makes
WeakSetconvenient for storing temporary or cached objects.
Real usage example
Tracking which objects have already been "processed":
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 is automatically removed from the WeakSetIn short:
| Property | Value |
|---|---|
| Type | A collection of unique objects |
| Primitives | Not allowed |
| Garbage collector | Can remove elements |
| Iteration | Not possible |
| Methods | add, delete, has |
| Common use | Caching, "processed" markers, private data |
Summary:
WeakSetis a collection of unique objects that are automatically removed from memory once there are no other references to them.
It is great for temporary markers and caching, it does not fit if you need to store data permanently or iterate over it.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.