Skip to content
Related Articles

Related Articles

Improve Article
JavaScript weakSet.add() Method
  • Difficulty Level : Easy
  • Last Updated : 17 Sep, 2020

Below is the example of weakSet.add() method.

  • Example:




    <script>  
        function gfg() {  
        const weakset = new WeakSet(); 
      
        const object1 = {}; 
        weakset.add(object1); 
        document.write(weakset.has(object1));  
        }  
        gfg();  
    </script>
  • Output:
    true

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.



Example:

Input: weakset.add(object1); 
Output: true

JavaScript code to show the working of the this function:

Code #1:




<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>

Output:

true
true
true
true

Code #2:




<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>

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.

Supported Browsers:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Apple Safari
  • Opera



My Personal Notes arrow_drop_up
Recommended Articles
Page :