Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptJavaScript weakSet add() Method

JavaScript weakSet add() Method

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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments