In JavaScript, the WeakSet object is used to store a collection of weakly held objects.
WeakSet is a built-in object that provides a way to store a collection of objects in a way that does not prevent them from being garbage collected when they are no longer needed.
This can be useful in certain cases where you need to store a reference to an object, but you don’t want to prevent the object from being garbage collected.
What is the WeakSet object?
The WeakSet object is a collection of objects that are held weakly.
This means that the WeakSet object does not prevent the objects from being garbage collected if there are no other references to them. The objects in a WeakSet can only be objects, and they must be unique (i.e., no duplicates are allowed). WeakSet is not iterable, meaning you cannot use the for...of
loop to iterate over the elements in the WeakSet.
The WeakSet object provides the following methods:
WeakSet.prototype.add(value)
: Adds the given value to the WeakSet.WeakSet.prototype.delete(value)
: Removes the given value from the WeakSet.WeakSet.prototype.has(value)
: Returns a boolean indicating whether the given value is in the WeakSet.
How does WeakSet work?
The WeakSet object uses weak references to hold its elements. A weak reference is a reference that does not prevent an object from being garbage collected. In other words, if an object only has weak references pointing to it, then the object can be garbage collected.
WeakSet does not prevent its elements from being garbage collected, as it holds weak references to its elements. This means that if an object is removed from the program’s memory, it will also be automatically removed from the WeakSet object.
Here is an example that shows how WeakSet works:
let weakSet = new WeakSet();
let obj = { a: 1 };
weakSet.add(obj);
console.log(weakSet.has(obj)); // true
obj = null;
console.log(weakSet.has(obj)); // false
In this example, we create a WeakSet object weakSet
, and add an object obj
to it. We then check if the object is in the WeakSet using the has()
method. Since the object is in the WeakSet, the method returns true
.
Next, we set the obj
variable to null
. This means that there are no more references to the object, and it is eligible for garbage collection. When we check if the object is still in the WeakSet using the has()
method, it returns false
since the object has been garbage collected.
Use cases for WeakSet
:
There are several use cases for WeakSet in JavaScript. Here are a few examples:
Caching
WeakSet can be used for caching. For example, suppose you have a function that takes an object as an argument and returns a result based on that object. If you call the function multiple times with the same object, you don’t want to recalculate the result every time. You can use a WeakSet to cache the result of the function for each object, like so:
const cache = new WeakSet();
function getResult(obj) {
if (cache.has(obj)) {
return cache.get(obj);
} else {
const result = /* calculate result based on obj */;
cache.add(obj, result);
return result;
}
}
In this example, we create a cache
WeakSet to store the results of the getResult()
function. When the function is called with an object, we check if the object is in the cache using the has()
method. If the object is in the cache, we retrieve the result using the get()
method and return it. Otherwise, we calculate the result based on the object, add it to the cache using the add()
method, and return the result.
Since the cache is a WeakSet, the cached results will be automatically removed from memory if the object is garbage collected.
Event listeners:
WeakSet can also be used to store event listeners. When an object is used as an event listener, it is typically added to an element’s event listener list.
If the object is not removed from the event listener list, it can prevent the object from being garbage collected, even if it is no longer needed. To avoid this, we can use a WeakSet to store the event listeners, like so:
const eventListeners = new WeakSet();
function addEventListener(obj, eventName, handler) {
obj.addEventListener(eventName, handler);
eventListeners.add(handler);
}
function removeEventListener(obj, eventName, handler) {
obj.removeEventListener(eventName, handler);
eventListeners.delete(handler);
}
In this example, we create a eventListeners
WeakSet to store the event handlers. When an event listener is added using the addEventListener()
function, we add the event handler to the eventListeners
WeakSet using the add()
method. When an event listener is removed using the removeEventListener()
function, we remove the event handler from the eventListeners
WeakSet using the delete()
method. Since the eventListeners
WeakSet holds weak references to the event handlers, they can be garbage collected if they are no longer needed.
Private properties:
WeakSet can also be used to store private properties on an object.
Since WeakSet holds weak references to its elements, the properties will be automatically removed from memory when the object is garbage collected.
Here’s an example:
const privateProperties = new WeakSet();
class MyClass {
constructor() {
privateProperties.add(this, { prop1: 1, prop2: 2 });
}
getPrivateProperty() {
return privateProperties.get(this);
}
}
In this example, we create a privateProperties
WeakSet to store private properties on an object. In the constructor of the MyClass
class, we add an object with two properties to the privateProperties
WeakSet using the add()
method. We then define a getPrivateProperty()
method that retrieves the private properties from the privateProperties
WeakSet using the get()
method. Since the privateProperties
WeakSet holds weak references to the objects, the private properties will be automatically removed from memory when the object is garbage collected.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.