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();
|
Example 2: Here the output is true because the newly created objects have been set to the end of the weakSet() object.
javascript
const weakset = new WeakSet();
const object1 = {};
const object2 = {};
const object3 = {};
const object4 = {};
weakset.add(object1);
weakset.add(object2);
weakset.add(object3);
weakset.add(object4);
console.log(weakset.has(object1));
console.log(weakset.has(object2));
console.log(weakset.has(object3));
console.log(weakset.has(object4));
|
Outputtrue
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
const weakset = new WeakSet();
const object1 = {};
const object2 = {};
const object3 = {};
const object4 = {};
console.log(weakset.has(object1));
console.log(weakset.has(object2));
console.log(weakset.has(object3));
console.log(weakset.has(object4));
|
Outputfalse
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.