JavaScript | WeakSet
WeakSet in JavaScript 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 the 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.
Some different WeakSet functions:
| METHODS | DESCRIPTION |
|---|---|
| add(value) | a new object is appended with the given value to the weakset. WeakSet_Object.add(value) |
| delete(value) | Deletes the value from the WeakSet collection. WeakSet_Object.delete(value) |
| has(value) | Returns true if the value is present in the WeakSet Collection, false otherwise. WeakSet_Object.has(value) |
| length() | Returns the length of weakSetObject WeakSet_Object.length() |
JavaScript code to show the working of WeakSet() function:
<script> var weakSetObject = new WeakSet(); var objectOne = {}; var objectTwo = {}; // add(value) weakSetObject.add(objectOne); document.write("objectOne added <br>"); weakSetObject.add(objectTwo); document.write("objectTwo added <br>"); // has(value) document.write("WeakSet has objectTwo : " + weakSetObject.has(objectTwo)); // delete(value) weakSetObject.delete(objectTwo); document.write("<br>objectTwo deleted<br>"); document.write("WeakSet has objectTwo : " + weakSetObject.has(objectTwo)); </script> |
Output:
objectOne added objectTwo added WeakSet has objectTwo : true objectTwo deleted WeakSet has objectTwo : false
Recommended Posts:
- JavaScript | weakSet.has() with Examples
- JavaScript | weakSet.delete() with Example
- JavaScript | weakSet.add() with Examples
- Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript
- How to compare two JavaScript array objects using jQuery/JavaScript ?
- JavaScript Course | Understanding Code Structure in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- JavaScript Course | Printing Hello World in JavaScript
- JavaScript Course | Logical Operators in JavaScript
- JavaScript Course | Data Types in JavaScript
- JavaScript Course | Variables in JavaScript
- JavaScript Course | Functions in JavaScript
- JavaScript Course | JavaScript Prompt Example
- JavaScript Course | Objects in JavaScript
- JavaScript Course | Loops in JavaScript
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


