- iterable: It is an iterable object, the elements of which will be added to a new WeakSet.
Advantages of using WeakSet object:
- The contents of a WeakSet can be garbage collected.
- Possibility of lowering memory utilization.
- Useful for class branding
Features of WeakSet object:
- A WeakSet object only includes unique items.
- If there is no reference to a stored object in WeakSet, it is targeted for garbage collection.
- The items in WeakSet are not enumerable. As a result, it does not provide any mechanism for obtaining the requested objects.
- It supports add, has, and delete like Set, but not size, keys(), or iterations.
Methods used with WeakSet object:
- add(value): In this method, value is appended to the WeakSet object.
- has(value): It returns a boolean indicating whether or not the value is present in the WeakSet object.
- delete(value): This method removes a value from the WeakSet. WeakSet.prototype.has(value) will then return false.
Example 1: In this example, we will use the WeakSet() constructor to build new WeakSets. This will generate a new WeakSet, which you can then use to store data in. When you use it to build a new WeakSet, you may supply an iterable containing value as an argument to it. To determine whether or not a given object exists in a WeakSet, use the has(value).
Example 2: In this example, we will create a WeakSet object with the weakset constructor and then added values with the add function. Following that, we verified whether or not the object we added were present. The object was then deleted from the weakset using the delete method, and then we have again verified that objects are successfully deleted or not.