JavaScript WeakSet

Understanding WeakSet and its special properties

🔒 What is a WeakSet?

A WeakSet is like a Set, but it can only store objects and has weak references. This means objects can be garbage collected even if they're in the WeakSet.


// WeakSet can only hold objects
const weakSet = new WeakSet();
const obj1 = { name: "John" };
const obj2 = { name: "Jane" };

weakSet.add(obj1);
weakSet.add(obj2);
                                    

WeakSet vs Set

🔒

WeakSet

Objects only, weak references

Objects only No iteration Garbage collection
📦

Set

Any values, strong references

Any values Iterable Size property

🔹 Creating a WeakSet

WeakSet can only store objects, not primitive values:

// Create a new WeakSet
const weakSet = new WeakSet();

// Objects to add
const user1 = { id: 1, name: "Alice" };
const user2 = { id: 2, name: "Bob" };

// Add objects to WeakSet
weakSet.add(user1);
weakSet.add(user2);

console.log("WeakSet created with objects");

Output:

WeakSet created with objects

🔹 WeakSet Methods

WeakSet has only three methods:

Available Methods:

  • add(object): Adds an object to the WeakSet
  • has(object): Checks if object exists
  • delete(object): Removes an object
const weakSet = new WeakSet();
const obj = { name: "Test" };

// Add object
weakSet.add(obj);
console.log("Has object:", weakSet.has(obj));

// Delete object
weakSet.delete(obj);
console.log("Has object after delete:", weakSet.has(obj));

Output:

Has object: true
Has object after delete: false

🔹 WeakSet Limitations

WeakSet has several important limitations:

const weakSet = new WeakSet();

// ❌ Cannot add primitive values
try {
    weakSet.add("string");  // This will throw an error
} catch (error) {
    console.log("Error:", error.message);
}

// ❌ Cannot iterate
// for (let item of weakSet) { } // This won't work

// ❌ No size property
console.log("Size:", weakSet.size); // undefined

// ✅ Only objects work
const obj = { data: "valid" };
weakSet.add(obj);
console.log("Object added successfully");

Output:

Error: Invalid value used in weak set
Size: undefined
Object added successfully

🔹 Garbage Collection Example

Objects in WeakSet can be garbage collected:

const weakSet = new WeakSet();

// Create an object and add to WeakSet
let obj = { name: "Temporary" };
weakSet.add(obj);

console.log("Object in WeakSet:", weakSet.has(obj));

// Remove the reference
obj = null;

// The object can now be garbage collected
// (even though it's still in the WeakSet)
console.log("Reference removed - object can be garbage collected");

Output:

Object in WeakSet: true
Reference removed - object can be garbage collected

🔹 Practical Use Cases

WeakSet is useful for tracking objects without preventing garbage collection:

🔸 Tracking Processed Objects

const processedObjects = new WeakSet();

function processData(obj) {
    if (processedObjects.has(obj)) {
        console.log("Already processed");
        return;
    }
    
    // Process the object
    console.log("Processing:", obj.name);
    processedObjects.add(obj);
}

// Example usage
const data1 = { name: "Dataset 1" };
const data2 = { name: "Dataset 2" };

processData(data1);  // Processing: Dataset 1
processData(data1);  // Already processed
processData(data2);  // Processing: Dataset 2

Output:

Processing: Dataset 1
Already processed
Processing: Dataset 2

🔹 When to Use WeakSet

Choose WeakSet when you need these specific features:

Use WeakSet when:

  • Object tracking: Track objects without preventing garbage collection
  • Memory efficiency: Don't want to hold strong references
  • Temporary associations: Associate data with objects temporarily

Use regular Set when:

  • Primitive values: Need to store strings, numbers, etc.
  • Iteration: Need to loop through values
  • Size tracking: Need to know how many items

🧠 Test Your Knowledge

What can you store in a WeakSet?