JavaScript WeakSet
A WeakSet in JavaScript is a collection of unique objects where the values are weakly referenced. It works similarly to a Set, but the objects stored in a WeakSet can be garbage-collected when no longer in use.
- A WeakSet can only store objects, not primitive values like strings or numbers.
- Objects in a WeakSet can be automatically removed when they are no longer referenced elsewhere, helping to manage memory efficiently.
Syntax
const weakSet=new WeakSet()
The syntax const weakSet = new WeakSet(); initializes a new empty WeakSet in JavaScript. It creates a collection that can only store objects and automatically removes objects when they are no longer in use.
How a Weak Set Works
- A WeakSet can only store objects as its values. Primitive values like numbers, strings, or booleans cannot be added.
- The objects stored in a WeakSet are weakly referenced, meaning that they can be garbage-collected if there are no other references to them.
- Unlike a regular Set, you cannot iterate over the values of a WeakSet (e.g., using forEach()), as it doesn't provide methods for iteration due to weak references.
- When an object in a WeakSet is no longer referenced elsewhere, it will be automatically removed from the WeakSet, helping to avoid memory s.
- A WeakSet only allows unique objects, meaning the same object cannot be added multiple times. However, it doesn't allow checking the size or accessing individual elements directly.
Components of a Weak Set
- Objects as data: A WeakSet can only store objects, not primitive values like numbers or strings.
- Weak References: The objects in a WeakSet are weakly referenced, which means they can be garbage-collected when no longer in use.
- Uniqueness: Each object in a WeakSet must be unique; duplicate objects are not allowed.
- No Iteration: You cannot loop through or access the items in a WeakSet.
- No Size Property: Unlike other collections, a WeakSet does not provide a way to check how many items it contains.
Implementation of Weak Set
This code demonstrates how to use a WeakSet in JavaScript to store and manage unique objects. It shows adding, checking, and removing objects, as well as how objects can be garbage collected when no longer referenced.
// Create a new WeakSet
let weakSet = new WeakSet();
// Create objects to use in the WeakSet
let obj1 = { name: "Pranjal" };
let obj2 = { name: "Pranav" };
weakSet.add(obj1);
weakSet.add(obj2);
weakSet.delete(obj1)
obj2=null
console.log(weakSet.has(obj1))
console.log(weakSet.has(obj2))
Output
false false
- Create a WeakSet: A new WeakSet is created using let weakSet = new WeakSet();. This will store only objects as keys.
- Add Objects: Two objects (obj1 and obj2) are created with names "Pranjal" and "Pranav", and added to the WeakSet using weakSet.add().
- Setting obj2 to null: The reference to obj2 is removed by setting it to null. Now, the object originally assigned to obj2 may be garbage collected since there are no other references to it.
- Check obj1 in WeakSet: The weakSet.has(obj1) checks if obj1 is still in the WeakSet. Since obj1 was not removed or garbage collected, it returns true.
- Check obj2 in WeakSet: The weakSet.has(obj2) checks if obj2 is in the WeakSet. Since obj2 is set to null and its object might be garbage collected, it returns false.
Functions present in Weak Set
- add(value): Adds an object to the WeakSet. If the object is not already in the set, it is added.
- has(value): Checks if the specified object exists in the WeakSet. Returns true if it exists, otherwise false.
- delete(value): Removes the specified object from the WeakSet. Returns true if the object was removed, otherwise false.
Coding Problems on Weak Set
- How to iterate over Set?
- Union of two Sets
- Intersection of two sets
- Element Ordering in a Set
- Sort a Set
- Array to Set
Advantages of Weak Set
- Memory Management: Objects in a WeakSet can be garbage collected when no longer in use, preventing memory s.
- No Duplicates: A WeakSet only stores unique objects, preventing duplicate entries and ensuring efficient data storage.
- Fast Lookups: Checking if an object is in a WeakSet is efficient, with constant time complexity (O(1)).
- Automatic Cleanup: When an object is no longer referenced elsewhere, it is automatically removed from the WeakSet, reducing the need for manual cleanup.
- Private Data: WeakSet is useful for storing private data, especially for associating metadata with objects without exposing it publicly.
Conclusion
In conclusion, a WeakSet in JavaScript is a powerful tool for managing collections of unique objects with automatic memory management. By allowing objects to be garbage collected when no longer referenced, it helps prevent memory s and ensures efficient resource usage. Though limited in features like iteration, its unique properties make it ideal for specific use cases such as storing private data and improving memory efficiency.