🌟 WeakSet In Javascript πŸš€

Nikhil Gupta
2 min readJun 2, 2024

--

Introduction

WeakSet emerges as a unique entity, offering an approach to handling collections of objects and symbols. Unlike traditional sets, WeakSet holds its elements weakly, meaning the elements can be garbage collected if there are no other references to them elsewhere in the code. This characteristic makes it an invaluable tool for detecting circular references and managing memory efficiently.🌿

🎯 What is WeakSet?

It is a collection designed to hold unique values, including objects and non-registered symbols, that are garbage collectable. This means that if there are no other references to an object stored in it, it can be safely garbage collected.

Key Differences Between WeakSet and Set

Unique Elements

Both `WeakSet` and `Set` ensure that each element occurs only once within the collection.

Garbage Collectable Values

  • Only objects and non-registered symbols can be stored in a `WeakSet` because they are garbage collectable.
  • Primitive values, lacking a lifetime, cannot be stored.

Non-Enumerability

Since `WeakSet` holds references weakly, it does not maintain a list of current values, making it non-enumerable.

πŸ”„ Why Use WeakSet?

It excels in scenarios where you need to track objects without preventing them from being garbage collected. This is particularly useful for detecting circular references in recursive functions, ensuring that the function does not enter an infinite loop.

Detecting Circular References

Consider a scenario where you have a recursive function that processes objects. To avoid processing the same object multiple times, you can use a `WeakSet` to keep track of objects that have already been processed.

function detectCircularReferences(obj) {
const seenObjects = new WeakSet();
const stack = [obj];
while (stack.length > 0) {
const currentObj = stack.pop();
if (seenObjects.has(currentObj)) {
continue;
}
seenObjects.add(currentObj);
stack.push(…Object.values(currentObj));
}
return seenObjects.size > 1;
}
const circularObj = {
prop1: {},
prop2: {}
};
circularObj.prop1.prop2 = circularObj; // Circular reference
console.log(detectCircularReferences(circularObj)); // true

πŸ› οΈ Constructor & Instance Methods

Creating it is straightforward:

const myWeakSet = new WeakSet();

Key methods include:

add(value): Adds a value to the `WeakSet`.

has(value): Checks if a value is present in the `WeakSet`.

delete(value): Removes a value from the `WeakSet`.

const ws = new WeakSet();
const obj1 = {};
const obj2 = {};
ws.add(obj1);
ws.add(obj2);
console.log(ws.has(obj1)); // true
console.log(ws.has(obj2)); // true
ws.delete(obj1);
console.log(ws.has(obj1)); // false
console.log(ws.has(obj2)); // true

🌈 Conclusion

  • WeakSet is a powerful tool in JavaScript for managing collections of objects and symbols without preventing them from being garbage collected.
  • Its ability to detect circular references and its efficient memory management make it indispensable for developers looking to optimize their code.
  • Whether you’re dealing with complex data structures or simply aiming to write cleaner, more efficient code it works in all.

If you enjoyed this article, please make sure to Like & Subscribe 🌐

For more updates Follow me on LinkedIn

--

--

Nikhil Gupta

πŸ‘¨β€πŸ’» Software Engineer | Passionate about Crafting Seamless User Experiences πŸš€