WeakSet Object
A WeakSet is a collection of objects, where each object can occur only once in the set. The objects in a WeakSet are held weakly, which means that if there are no other references to an object stored in the WeakSet, that object can be garbage collected. This makes WeakSet particularly useful for keeping track of objects without preventing their garbage collection.
Key Features
- Weak References: Objects are held weakly, allowing them to be garbage collected if there are no other references.
- Non-iterable:
WeakSetis not iterable, meaning it cannot be used in afor...ofloop or spread operator. - Only Object Values: Only objects can be stored in a
WeakSet. Primitive values cannot be stored.
Practical Examples
Example 1: Tracking Objects
You can use a WeakSet to keep track of objects without preventing their garbage collection.
const weakSet = new WeakSet();
let obj1 = { name: 'Alice' };
let obj2 = { name: 'Bob' };
weakSet.add(obj1);
weakSet.add(obj2);
console.log(weakSet.has(obj1)); // Output: true
console.log(weakSet.has(obj2)); // Output: true
obj1 = null; // obj1 is eligible for garbage collection
// obj1 will be removed from the WeakSet during garbage collection
console.log(weakSet.has(obj1)); // Output: false (after garbage collection)
Example 2: Preventing Repeated Operations
You can use a WeakSet to track objects that have already been processed to avoid repeated operations.
const processed = new WeakSet();
function process(obj) {
if (processed.has(obj)) {
console.log('Already processed:', obj);
} else {
console.log('Processing:', obj);
processed.add(obj);
// Perform processing on the object
}
}
let obj1 = { id: 1 };
let obj2 = { id: 2 };
process(obj1); // Output: Processing: { id: 1 }
process(obj1); // Output: Already processed: { id: 1 }
process(obj2); // Output: Processing: { id: 2 }
Example 3: Memory Management in Event Listeners
Using a WeakSet to manage objects referenced by event listeners, allowing for better memory management.
const listeners = new WeakSet();
function addListener(element, callback) {
if (!listeners.has(callback)) {
element.addEventListener('click', callback);
listeners.add(callback);
}
}
const button = document.createElement('button');
button.textContent = 'Click me';
document.body.appendChild(button);
const handleClick = () => {
console.log('Button clicked');
};
addListener(button, handleClick); // Adds event listener
addListener(button, handleClick); // Does not add again
button.remove(); // When button is removed, handleClick is eligible for garbage collection