JavaScript WeakSet is used to store a collection of objects. It adapts the same properties of that of a set i.e. does not store duplicates. The major difference of a WeakSet with a set is that a WeakSet is a collection of objects and not values of some particular type.
Syntax:
new WeakSet(object)
Parameters: Here parameter “object” is an iterable object. All the elements of the iterable object are added to the WeakSet.
Return type: It returns a weakset object.
Example 1: In this example, we will create a weakSet object and add an element to it, then we will check if the element exists in the weakSet. We will use has() method and add() method
javascript
function gfg() {
let weakSetObject = new WeakSet();
let objectOne = {};
weakSetObject.add(objectOne);
console.log( "objectOne added" );
console.log( "WeakSet has objectOne : " +
weakSetObject.has(objectOne));
}
gfg();
|
Output:
objectOne added
true
Example 2: In this example, we will see the working of weakSet functions also we will delete data using the delete() method.
javascript
let weakSetObject = new WeakSet();
let objectOne = {};
let objectTwo = {};
weakSetObject.add(objectOne);
console.log( "objectOne added" );
weakSetObject.add(objectTwo);
console.log( "objectTwo added" );
console.log( "WeakSet has objectTwo : " +
weakSetObject.has(objectTwo));
weakSetObject. delete (objectTwo);
console.log( "objectTwo deleted" );
console.log( "WeakSet has objectTwo : " +
weakSetObject.has(objectTwo));
|
Output:
objectOne added
objectTwo added
WeakSet has objectTwo : true
objectTwo deleted
WeakSet has objectTwo : false
Supported Browsers:
- Google Chrome
- Internet Explorer
- Firefox
- Apple Safari
- Opera
We have a complete list of Javascript weakSet methods, to check those please go through this JavaScript WeakSet Reference article.