WeakSet Basics and Operations
What you'll learn: How to create and use WeakSets to track object membership without preventing garbage collection.
What is a WeakSet?
A WeakSet is like a Set, but it only holds objects (not primitives) and holds them weakly. This means if an object in a WeakSet has no other references in your program, it can be garbage collected—and it will automatically disappear from the WeakSet. This makes WeakSets perfect for tracking which objects have been processed or marked, without creating memory leaks.
Think of it like a guest list at an exclusive event: you can only add actual people (objects), not just names (primitives). When a person leaves town permanently (no other references exist), they're automatically removed from your list.
Creating and Using WeakSets
const visitedObjects = new WeakSet();
const user1 = { name: 'Alice' };
const user2 = { name: 'Bob' };
// Add objects to track them
visitedObjects.add(user1);
visitedObjects.add(user2);
// Check membership
console.log(visitedObjects.has(user1)); // true
// Delete an object
visitedObjects.delete(user2);
console.log(visitedObjects.has(user2)); // false
// Cannot add primitives
// visitedObjects.add('string'); // TypeError!
Key Characteristics
WeakSets have only three methods:
add(object)– Add an object to the sethas(object)– Check if an object existsdelete(object)– Remove an object
Unlike regular Sets, WeakSets are not iterable and have no size property. You can't loop through them or count entries because the contents may change unpredictably as garbage collection happens.
Key Takeaway: WeakSets track object membership weakly using add(), has(), and delete(), automatically cleaning up when objects are no longer referenced elsewhere—ideal for metadata without memory leaks.