JavaScript – Weak Set


What is a Weakset ?

Weakset is a javascript object used to store the collection of objects.

It allows us to store unique objects with some particular type.

It doesn’t store the duplicate values.

Syntax :

new WeakSet([iterable])  

Iterable:


It defines the iterable object whose elements will be added to a new WeakSet.

Example :

<script>  
                        var weakset = new WeakSet();  
                        var obj1={};  
                        var obj2={};  
                        weakset.add(obj1);  
                        weakset.add(obj2);  
                        console.log(weakset);  
                </script>  

Output :

How weakset works in javascript ?

WeakSet object can contain only unique objects.

There will not be any reference to the stored objects, once processed it will be moved to the garbage collection.

WeakSet objects are not enumerable, so it has not methods to get the specific objects.

Methods of WeakSet Object

Weakset is used to store the collection of objects, and some of the methods are listed below.


SnoMethod / FunctionDescription
1add()add() method adds a new object to the end of WeakSet object.
2delete()delete() method deletes the specified object from the WeakSet object.
3has()has() method indicates whether the WeakSet object contains the specified object element.

Free online javascript course !!!

Click to Learn More about – Javascript online learning