JavaScript WeakSet
A WeakSet is a collection of objects where each object must be unique. Unlike regular Sets in JavaScript, WeakSets hold “weak” references to the objects they store. This means that if an object is present only in a WeakSet and is not referenced elsewhere in the code, it becomes eligible for garbage collection.For example,
const weakSet = new WeakSet();
console.log(weakSet); // WeakSet {}
let obj = {
message: 'Hi',
sendMessage: true
}
// adding object (element) to WeakSet
weakSet.add(obj);
console.log(weakSet); // WeakSet {{message: "Hi", sendMessage: true}}
In the below PDF we discuss about Javascript WeakSet in detail in simple language, Hope this will help in better understanding.
WeakSet Methods:
WeakSets have methods add(), delete(), and has(). For example,
const weakSet = new WeakSet();
console.log(weakSet); // WeakSet {}
const obj = {a:1};
// add to a weakSet
weakSet.add(obj);
console.log(weakSet); // WeakSet {{a: 1}}
// check if an element is in Set
console.log(weakSet.has(obj)); // true
// delete elements
weakSet.delete(obj);
console.log(weakSet); // WeakSet {}
Key Characteristics:
- Uniqueness of Elements: Similar to Sets, WeakSets only allow unique elements. In other words, no duplicate elements are permitted within a WeakSet.
- Weak References: The most distinctive feature of WeakSets is their use of weak references. Objects stored in a WeakSet do not prevent garbage collection, making it useful for scenarios where you want to associate data with objects without preventing them from being cleaned up by the garbage collector.
- No Iteration: Unlike Sets, WeakSets do not provide methods for iterating over their elements or checking the size of the collection. This limitation is due to the unpredictable nature of garbage collection.
Related Question
A WeakSet is a built-in object in JavaScript that allows you to store a collection of unique objects. Unlike a Set, a WeakSet can only contain objects, and these objects are held weakly, meaning they do not prevent the objects from being garbage collected.
You can create a WeakSet using the new WeakSet() constructor.
The key feature of a WeakSet is that it holds references to objects weakly. This means that if there are no other references to an object stored in the WeakSet, it can be automatically garbage collected.
No, a WeakSet can only contain objects, and attempts to add primitive values like numbers or strings will result in a TypeError.
Relevant
JavaScript Function Generator WhatsApp Group
JavaScript WeakMap WhatsApp Group Join
JavaScript Proxy WhatsApp Group Join
JavaScript Boolean WhatsApp Group Join
JavaScript BigInt WhatsApp Group Join
JavaScript Promise WhatsApp Group Join