Lesson 84 – WeakSets in JavaScript
WeakSet` is a special kind of Set that only stores objects, and those objects are held weakly—meaning they don’t prevent garbage collection if there are no other references to them.
What is a WeakSet?
- Like a
Set
, aWeakSet
lets you store unique values. - But only objects (not primitives) can be added.
- Objects in a
WeakSet
are held weakly. WeakSet
is not iterable and has nosize
property.
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
ws.delete(obj2);
console.log(ws.has(obj2)); // false
Limitations of WeakSet
- You cannot list all elements.
- You can't use
.forEach()
or get.size
. - You can only use
.add()
,.has()
, and.delete()
.
const ws = new WeakSet();
ws.add(1); // Error: Invalid value used in weak set
Use Case: Tracking Objects Without Preventing GC
WeakSets are good for storing metadata or tracking object states without interfering with memory cleanup.
Example:
const visitedNodes = new WeakSet();
function visit(node) {
if (visitedNodes.has(node)) {
console.log("Already visited");
return;
}
visitedNodes.add(node);
console.log("Visiting", node);
}
Try Your Hand
- Create a
WeakSet
and add 2 different objects. - Check if a third object is in the set.
- Delete one and check the result.
- Try adding a primitive (and see the error).