JavaScript | WeakSet

WeakSet in JavaScript is used to store a collection of objects. It adapts the same properties of that of a set i.e. does not store duplicates. The major difference of a WeakSet with the set is that a WeakSet is a collection of objects and not values of some particular type.
Syntax:

new WeakSet(object)

Parameters: Here parameter “object” is an iterable object. All the elements of the iterable object are added to the WeakSet.
Some different WeakSet functions:

METHODS DESCRIPTION
add(value) a new object is appended with the given value to the weakset.
WeakSet_Object.add(value)
delete(value) Deletes the value from the WeakSet collection.
WeakSet_Object.delete(value)
has(value) Returns true if the value is present in the WeakSet Collection, false otherwise.
WeakSet_Object.has(value)
length() Returns the length of weakSetObject
WeakSet_Object.length()

JavaScript code to show the working of WeakSet() function:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
    var weakSetObject = new WeakSet();
    var objectOne = {};
    var objectTwo = {};
  
    // add(value)
    weakSetObject.add(objectOne);
    document.write("objectOne added <br>");
    weakSetObject.add(objectTwo);
    document.write("objectTwo added <br>");
  
    // has(value)
    document.write("WeakSet has objectTwo : "
                    weakSetObject.has(objectTwo));
  
    // delete(value)
    weakSetObject.delete(objectTwo);
    document.write("<br>objectTwo deleted<br>");
    document.write("WeakSet has objectTwo : "
                    weakSetObject.has(objectTwo));
  
</script>                    

chevron_right


Output:

objectOne added 
objectTwo added 
WeakSet has objectTwo : true
objectTwo deleted
WeakSet has objectTwo : false


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.