WeakSet in JavaScript (Live Playground)
In JavaScript, the WeakSet
data structure is a collection that holds weakly referenced unique objects. WeakSets are designed to prevent memory leaks, as they do not prevent their objects from being garbage collected. In this tutorial, we will explore the WeakSet
data structure and its methods.
Creating a WeakSet
To create a WeakSet
, use the WeakSet
constructor. You can create an empty WeakSet or initialize it with an iterable object containing objects:
Example:
const emptyWeakSet = new WeakSet();
const objects = [
{ id: 1, name: 'Object 1' },
{ id: 2, name: 'Object 2' },
{ id: 3, name: 'Object 3' },
];
const objectWeakSet = new WeakSet(objects);
Note that only objects can be stored in a WeakSet. Primitive values such as numbers or strings will throw a TypeError.
Adding Elements
To add an object to a WeakSet, use the add
method:
const myWeakSet = new WeakSet();
const obj1 = { id: 1, name: 'First Object' };
const obj2 = { id: 2, name: 'Second Object' };
myWeakSet.add(obj1);
myWeakSet.add(obj2);
Removing Elements
Since WeakSets hold weak references to objects, you don't need to remove elements explicitly. When an object is no longer reachable, it will be garbage collected along with its WeakSet entry.
Checking for Elements
To check if a WeakSet contains a specific object, use the has
method:
myWeakSet.has(obj1); // Returns true if the object is in the WeakSet, otherwise false.
Limitations of WeakSets
WeakSets do not provide methods to access or remove individual elements, nor do they provide a method to iterate over the set. They also do not have a size
property.
Conclusion
In this tutorial, we have covered the WeakSet
data structure in JavaScript, which is designed to hold weakly referenced unique objects. We've learned how to create a WeakSet, add objects, and check for objects in the set. WeakSets can be useful when you need to store a collection of objects without preventing them from being garbage collected.