How to Use the weakSet.add() Method in JavaScript

Here’s an example weakSet.add() method.

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

The output is as follows: true

weakSet.add() is a built-in function in JavaScript that is used to add a weak set of objects at the end of an object. With the WeakSet object, you can store weakly saved objects in a collection.

The syntax is as follows:

weakSet.add(A);

Parameter: It accepts the parameter “A”, which is the value that will be added to the weakened object.

Return Value: It returns the weakened object.

Example:

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

The JavaScript code shows how this feature works:

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>

The output is as follows:

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>

The output is as follows:

false
false
false
false

The output here is false, because the newly created object has not yet been set to the end of the weakSet() object.

Supported browsers:

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