Chapter XXIV · Advanced Concepts

WeakSet

A `WeakSet` is a collection containing only unique object references held weakly, making them eligible for garbage collection.

01 How It Works

Think of a temporary visitor guest check-in list that clears out once visitors leave.

WeakSets are not iterable and do not prevent their stored object items from being garbage collected.

example.js
const ws = new WeakSet();
let obj = { active: true };
ws.add(obj);
console.log(ws.has(obj)); // true
  1. 1. Initialize a `WeakSet` instance.

  2. 2. Add object references using `.add(obj)`.

  3. 3. Check existence with `.has(obj)`.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
const visitedNodes = new WeakSet();
function markVisited(node) {
  visitedNodes.add(node);
}

Key Takeaway

WeakSets store object collections weakly without preventing garbage collection.

Related Concepts