Tutorialspoint.dev

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:

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



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter