Below is the example of weakSet.add() method.
- Example:
<script>
function
gfg() {
var
weakSetObject =
new
WeakSet();
var
objectOne = {};
// add(value)
weakSetObject.add(objectOne);
document.write(
"objectOne added </br>"
);
// has(value)
document.write(
"WeakSet has objectTwo : "
+
weakSetObject.has(objectTwo));
}
gfg();
</script>
chevron_rightfilter_none - Output:
objectOne added
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
Supported Browsers:
- Google Chrome
- Internet Explorer
- Firefox
- Apple Safari
- Opera