What is WeakSet in JavaScript: Explanation and Examples
WeakSet in JavaScript is a special collection that stores objects only and holds them weakly, meaning it does not prevent garbage collection if there are no other references. It allows you to track objects without creating strong references, useful for memory-efficient object management.How It Works
A WeakSet is like a regular set but only holds objects, not primitive values like numbers or strings. The key difference is that the references to these objects are "weak." This means if no other part of your program is using an object stored in the WeakSet, JavaScript can remove it from memory automatically.
Think of it like a sticky note on a book that you can easily remove if the book is no longer needed anywhere else. This helps avoid memory leaks because the WeakSet does not keep objects alive by itself.
Because of this weak reference, you cannot list or iterate over the items in a WeakSet. It only lets you add, check, or delete objects.
Example
This example shows how to add objects to a WeakSet, check if an object is inside it, and delete an object.
const ws = new WeakSet(); let obj1 = { name: 'apple' }; let obj2 = { name: 'banana' }; ws.add(obj1); console.log(ws.has(obj1)); // true console.log(ws.has(obj2)); // false ws.delete(obj1); console.log(ws.has(obj1)); // false
When to Use
Use WeakSet when you want to keep track of objects without preventing them from being cleaned up by JavaScript's memory system. This is useful in cases like caching, tracking DOM elements, or managing listeners where you don't want to cause memory leaks.
For example, if you want to remember which objects have been processed but don't want to keep them forever, a WeakSet is a good choice because it automatically forgets objects that are no longer used elsewhere.
Key Points
- Only objects:
WeakSetcan only store objects, not primitives. - Weak references: Objects in a
WeakSetdo not prevent garbage collection. - No iteration: You cannot loop over a
WeakSetbecause its contents can change automatically. - Use cases: Useful for memory-sensitive tracking like caching or DOM element management.