JavaScript WeakSet

This tutorial is about JavaScript WeakSet, a new data structure introduced in ES6. WeakSet is a Set object that only stores weakly held objects and is not iterable. The WeakSet object is especially useful when dealing with memory management, as it helps to prevent memory leaks.

Why should you use it?

  • WeakSet helps to prevent memory leaks.
  • It allows you to store weakly held objects.
  • It is not iterable, so it is more secure.

WeakSet

WeakSet is a collection of objects, similar to Set, but with a few key differences. WeakSet only accepts objects, and they are weakly held, meaning that they can be garbage collected if there is no other reference to them. WeakSet also does not have a size property, nor any methods that act upon the size of the collection.

WeakSets are useful for keeping track of objects without preventing them from being garbage collected. An example of this would be keeping track of DOM nodes without having to remove them from the DOM manually.

Creating a WeakSet

WeakSets are created using the WeakSet constructor, which takes an iterable of objects as its argument.

script.js
let myWeakSet = new WeakSet([{}, {}]);
console.log(myWeakSet);

In the above example, we create a WeakSet called myWeakSet, and add two objects to it.

Adding and Removing Objects

Objects can be added to and removed from WeakSets using the add() and delete() methods.

script.js
let myWeakSet = new WeakSet();
let obj1 = {};
let obj2 = {};

myWeakSet.add(obj1);
myWeakSet.add(obj2);

myWeakSet.delete(obj1);

console.log(myWeakSet);

In the above example, we add an object to myWeakSet, and then remove it using the delete() method.

Checking for Objects

WeakSets do not have a has() method, so the only way to check for the presence of an object in a WeakSet is to use the has() method of the Set.prototype object.

script.js
let myWeakSet = new WeakSet([{}, {}]);
let obj1 = {};

console.log(Set.prototype.has.call(myWeakSet, obj1));

In the above example, we create a mySet, and use the has() method of the Set.prototype object to check if an object is present in the WeakSet.

Iterating over WeakSets

WeakSets do not have a forEach() method, so the only way to iterate over a WeakSet is to use the forEach() method of the Set.prototype object.

script.js
let myWeakSet = new WeakSet([{}, {}]);

Set.prototype.forEach.call(myWeakSet, (value) => {
  console.log(value);
});

In the above example, we create a mySet, and use the forEach() method of the Set.prototype object to iterate over the WeakSet.