JavaScript WeakSet() Constructor
Last Updated :
22 May, 2023
JavaScript WeakSet Constructor is used to create a weakset that is similar to the set as it does not contain duplicate objects. It is different from the set as it stores a collection of weakly held objects instead of an object of a particular type.
We can only create a WeakSet with the new keyword otherwise a TypeError will be thrown
Syntax:
new WeakSet()
new WeakSet(iter)
Parameter: It has one optional parameter.
- iter: It is an iterable object whose elements will be assigned to new WeakSet. If null is given it will be treated as undefined.
Return Type: A WeakSet object
Example 1: In this example, we will create a WeakSet object and add elements to it.
Javascript
let x = new WeakSet();
let y = new WeakSet( null );
x.add({});
x.add({});
console.log(x);
console.log(y);
|
Output:
WeakSet {{…}, {…}}
WeakSet {}
Example 2: In this example, we will add objects with values in WeakSet and check if the element is inserted with inbuilt methods.
Javascript
let looseSet = new WeakSet();
let Rahul = {name: "Rahul" };
let Vijay = {name: "Vijay" }
let Ram = {name: "Ram" }
looseSet.add(Rahul);
looseSet.add(Vijay);
console.log(looseSet.has(Rahul));
console.log(looseSet.has(Ram));
|
Output:
true
false
Supported Browsers:
- Google Chrome
- Firefox
- Internet Explorer
- Opera
- Safari
We have a complete list of Javascript weakSet methods, to check those please go through this JavaScript WeakSet Complete Reference article.
Share your thoughts in the comments
Please Login to comment...