What is the WeakSet object in JavaScript?
Overview
In JavaScript, we use a WeakSet object to store a collection of objects. It has the following characteristics:
- It can only contain objects as a value.
- Objects stored are unique. The same object cannot be repeated. If so, the duplicated object will be ignored.
- Objects are "weakly stored." If there are no other references besides
WeakSet, the object will be removed from memory. This is known as garbage collection.
Syntax
const weakSet = new WeakSet([iterable])
Methods
We use three types of methods in the WeakSet object.
add(): We use this to add objects to theWeakSetobject.has(): We use this to return a boolean, verifying whether or not a value is present in theWeakSetobject.delete(): We use this to delete a value from theweakSetobject.
Example
let obj = new WeakSet();console.log(obj);let objOne = {greeting: "Hi"};obj.add(objOne)console.log(`weakSet has objOne:`+ obj.has(objOne))obj.delete(objOne)console.log(`weakSet has objOne:`+ obj.has(objOne))
Explanation
- Line 1–2: We'll create an empty
weakSet()object. - Line 4-5: We'll use the
addmethod to attach the object to theweakSet. - Line 7: We use the
hasmethod to verify if the object is present in theweakSet. - Line 9–10: We'll use the
deletemethod to remove the object from theweakSet.