Open In App

What is the use of a WeakSet object in JavaScript ?

Introduction: The JavaScript WeakSet object is a sort of collection that allows us to store items that are only loosely held. WeakSet, unlike Set, is just a collection of items. It does not include arbitrary values. It has the same features as a set, in that it does not hold duplicates. The main distinction between a WeakSet and a set is that a WeakSet is a collection of objects rather than values of a certain type. It supports add, has, and delete like Set, but not size, keys(), or iterations.

Syntax:



new WeakSet([iterable])  

Parameter:

Advantages of using WeakSet object:



Features of WeakSet object:

Methods used with WeakSet object:

Example 1: In this example, we will use the WeakSet() constructor to build new WeakSets. This will generate a new WeakSet, which you can then use to store data in. When you use it to build a new WeakSet, you may supply an iterable containing value as an argument to it. To determine whether or not a given object exists in a WeakSet, use the has(value).




const gfg = {},
geeks = {};  
const obj = new WeakSet([gfg, geeks]);
  
// Checking if gfg exists
console.log(obj.has(gfg));

Output:

true

Example 2: In this example, we will create a WeakSet object with the weakset constructor and then add values with the add function. Following that, we verified whether or not the object we added were present. The object was then deleted from the weakset using the delete method, and then we again verified that the objects are successfully deleted or not.




const obj = new WeakSet();
const gfg = {};
const geeks = {};
  
// gfg object added
obj.add(gfg);
console.log(obj.has(gfg)) // true
console.log(obj.has(geeks)) // false
  
// gfg object removed
obj.delete(gfg);
console.log(obj.has(gfg)) // false

Output:

true
false
false

Article Tags :