JavaScript - WeakSet

WeakSet, like WeakMap, is a collection that stores things weakly, allowing garbage collection if there are no other references to the object. The distinction between WeakSet and a conventional Set is that WeakSet only holds objects (no primitive types like numbers or strings) and cannot contain duplicates.

WeakSet is useful for tracking things without having to worry about them taking up too much memory. One practical application is keeping track of which items have been processed without consuming memory by retaining references to objects that are no longer required.

Here’s a basic example of using WeakSet:

let weak_Set = new WeakSet();

let obj1 = {name: 'Object 1'};

let obj2 = {name: 'Object 2'};

weak_Set.add(obj1);

weak_Set.add(obj2);

console.log(weakSet.has(obj1)); // true

obj1 = null; // obj1 is now eligible for garbage collection

When obj1 is set to null, it is automatically deleted from the WeakSet, making it an economical solution for cases in which objects are added temporarily and then cleaned up as soon as they are no longer referenced.