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.
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.
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)); // true
console.log(looseSet.has(Ram)); // false
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.

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.
