Course contentsShow
← JavaScript
Lesson 1061 of 2,72324. Maps and SetsFree lesson

WeakSet Use Case: Tracking Object Sets

Using WeakSet to mark objects as processed or track unique instances.

WeakSet Use Case: Tracking Object Sets

You'll learn how to use WeakSet to efficiently mark objects as processed or track unique instances without preventing garbage collection.

The Core Idea

A WeakSet is perfect when you need to keep track of which objects you've already seen or processed, but you don't want to prevent those objects from being cleaned up when they're no longer needed elsewhere in your code. Think of it like putting invisible sticky notes on objects—you can check if an object has a note, but the note won't keep the object alive if nothing else needs it.

Common Use Cases

Tracking Processed Objects

When processing a data structure, you might need to avoid re-processing the same object:

const processedObjects = new WeakSet();

function processNode(node) {
  if (processedObjects.has(node)) {
    return; // Already processed
  }
  
  processedObjects.add(node);
  // ... do the actual processing
}

Marking Unique Instances

Track which specific object instances belong to a certain category:

const authenticatedUsers = new WeakSet();

function login(user) {
  authenticatedUsers.add(user);
}

function isLoggedIn(user) {
  return authenticatedUsers.has(user);
}

The beauty here: when a user object is no longer referenced anywhere, it automatically gets removed from the WeakSet.

Why Not Use a Regular Set?

A regular Set would keep those objects alive forever, even if your application is done with them. WeakSet lets objects be garbage collected naturally when they're no longer needed.

Key Takeaway: Use WeakSet when you need to track which objects you've encountered (like marking them as "processed" or "authenticated") without affecting their lifecycle—perfect for temporary flags and metadata that shouldn't prevent cleanup.