JavaScript | weakSet.add() with Examples

The weakSet.add() is an inbuilt function in JavaScript which is used to add an object at the end of the a object WeakSet. The WeakSet object lets you store weakly held objects in a collection.

Syntax:

weakSet.add(A);

Parameters: It accepts the parameter “A” which is a value going to be added to the weakset object.
Return Values: It returns the weakset object.

JavaScript code to show the working of the this function:

Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
    // Constructing a weakset object
    const weakset = new WeakSet();
  
    // Constructing a new object object1
    const object1 = {};
    const object2 = {};
    const object3 = {};
    const object4 = {};
  
    // Adding the object1 at the end of the weakset object.
    weakset.add(object1);
    weakset.add(object2);
    weakset.add(object3);
    weakset.add(object4);
  
    // Printing either object has been added or not
    document.write(weakset.has(object1) +"<br>");
    document.write(weakset.has(object2) +"<br>");
    document.write(weakset.has(object3) +"<br>");
    document.write(weakset.has(object4));
      
</script>

chevron_right


Output:

true
true
true
true

Code #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
    // Constructing a weakset object
    const weakset = new WeakSet();
  
    // Constructing a new object object1
    const object1 = {};
    const object2 = {};
    const object3 = {};
    const object4 = {};
  
    // Printing either object has been added or not
    document.write(weakset.has(object1) +"<br>");
    document.write(weakset.has(object2) +"<br>");
    document.write(weakset.has(object3) +"<br>");
    document.write(weakset.has(object4));
      
</script>

chevron_right


Output:

false
false
false
false

Here the output is false because the new created objects has not been set to the end of the weakSet() object.



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.