In JavaScript, a WeakSet is a built-in object that allows us to store a collection of weakly held objects.
Unlike a regular Set, a WeakSet can only contain objects, and the references to these objects are held weakly. This means that if there are no other references to an object stored in a WeakSet, it may be automatically garbage collected.
Here's a basic overview of how we can use WeakSet in JavaScript:
// Creating an empty WeakSet let yourWeakSet = new WeakSet(); // Adding objects to the WeakSet let obj1 = { key: 'value' }; let obj2 = { name: 'Alice' }; yourWeakSet.add(obj1); yourWeakSet.add(obj2);
add(value): Adds an object to the `WeakSet`. The value must be an object.
// Creating an empty WeakSet let yourWeakSet = new WeakSet(); // Adding objects to the WeakSet let obj1 = { key: 'value' }; let obj2 = { name: 'Alice' }; yourWeakSet.add(obj1); yourWeakSet.add(obj2); let obj3 = { age: 35 }; yourWeakSet.add(obj3);
console.log(yourWeakSet.has(obj1)); // true console.log(yourWeakSet.has(obj4)); // false
yourWeakSet.delete(obj2);
has(value): Returns a boolean indicating whether the `WeakSet` contains a specific object.
delete(value): Removes an object from the WeakSet.
The key distinction between a regular Set and a WeakSet is the "weak" reference behaviour.
In a WeakSet, the references to the objects are held weakly, meaning that if there are no other references to an object, it can be automatically garbage collected.
This behaviour is particularly useful when dealing with scenarios where we want to associate additional data with an object temporarily, and we don't want to prevent the object from being garbage collected when it's no longer needed.
let weakSet = new WeakSet(); let objA = { name: 'Alice' }; let objB = { name: 'Bob' }; weakSet.add(objA); weakSet.add(objB); console.log(weakSet.has(objA)); // true console.log(weakSet.has(objB)); // true // Removing objA reference objA = null; // At this point, objA may be garbage collected, and weakSet may no longer have a reference to it
`WeakSet` is not iterable, meaning we cannot loop over its elements directly. Additionally, it doesn't have methods like size or clear that are available in regular `Set` objects.
`WeakSet` is useful in scenarios where we want to associate auxiliary data with objects without preventing those objects from being automatically garbage collected when they are no longer needed.