Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

JavaScript weakSet.add() Method

  • Difficulty Level : Easy
  • Last Updated : 13 Dec, 2021

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 36 and above
  • Firefox 34 and above
  • Apple Safari 9 and above
  • Opera 23 and above
  • Edge 12 and above

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!