The Wayback Machine - https://web.archive.org/web/20240213201236/https://www.geeksforgeeks.org/javascript-weakset/
Open In App
Related Articles

JavaScript WeakSet

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 = {};
     
    // add(value)
    weakSetObject.add(objectOne);
    console.log("objectOne added");
     
    // has(value)
    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 = {};
 
// add(value)
weakSetObject.add(objectOne);
console.log("objectOne added");
weakSetObject.add(objectTwo);
console.log("objectTwo added");
 
// has(value)
console.log("WeakSet has objectTwo : " +
weakSetObject.has(objectTwo));
 
// delete(value)
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.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks 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!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!


Last Updated : 22 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials