Open In App

JavaScript weakSet add() Method

Last Updated : 07 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Syntax:

weakSet.add(A);

Parameters: This method accepts a single parameter value.

  • value: This value will be added to the weakset object. 

Return Values: It returns the newly added weakset object.

Below are examples of weakSet.add() method:

Example 1: This is a basic example of weakset.add() method in javascript.

javascript




function gfg() {
    const weakset = new WeakSet();
 
    const object1 = {};
    weakset.add(object1);
    console.log(weakset.has(object1));
}
gfg();


Output

true


Example 2: Here the output is true because the newly created objects have been set to the end of the weakSet() object.

javascript




// 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
console.log(weakset.has(object1));
console.log(weakset.has(object2));
console.log(weakset.has(object3));
console.log(weakset.has(object4));


Output

true
true
true
true


Example 3: Here the output is false because the newly created objects have not been set to the end of the weakSet() object.

javascript




// 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
console.log(weakset.has(object1));
console.log(weakset.has(object2));
console.log(weakset.has(object3));
console.log(weakset.has(object4));


Output

false
false
false
false


Supported Browsers:

  • Google Chrome 36 and above
  • Firefox 34 and above
  • Apple Safari 9 and above
  • Opera 23 and above
  • Edge 12 and above

We have a complete list of Javascript WeakSet methods, to check those please go through Javascript WeakSet Complete reference article.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads