javascript
  1. javascript-weakset

JavaScript WeakSet

WeakSet is a new data structure introduced in ES6 (ECMAScript 2015). It allows you to store a collection of unique objects just like Set, but with one major difference. The objects stored in WeakSet can be garbage collected if there are no references to them.

Syntax

To create a WeakSet, you can use the following syntax:

const weakSet = new WeakSet();

Adding and Removing Elements

To add an element to a WeakSet, you can use the add() method. Similarly, you can remove an element using delete() method.

const weakSet = new WeakSet();
const obj1 = {};
const obj2 = {};

weakSet.add(obj1);
weakSet.add(obj2);

weakSet.has(obj1); // true
weakSet.has(obj2); // true

weakSet.delete(obj1);

weakSet.has(obj1); // false

WeakSet vs. Set

WeakSet is similar to Set in many ways, but there are a couple of differences:

  • WeakSet can only contain objects, whereas Set can contain any value.
  • WeakSet elements can be garbage collected, whereas Set elements cannot.

Example

const weakSet = new WeakSet();

let obj1 = { name: "John" };
let obj2 = { name: "Jane" };
let obj3 = { name: "Jack" };

weakSet.add(obj1);
weakSet.add(obj2);

console.log(weakSet.has(obj1)); // true
console.log(weakSet.has(obj2)); // true
console.log(weakSet.has(obj3)); // false

Output

true
true
false

Explanation

In the above example, we have created a WeakSet and added two objects obj1 and obj2 to it using the add() method. We have also created another object obj3 but we have not added it to the WeakSet.

We have then used the has() method to check if the objects exist in the WeakSet. Since we added obj1 and obj2 to the WeakSet, it returns true for those objects. However, since obj3 was not added, it returns false.

Use

WeakSet can be very useful when you need to store a collection of objects that are only needed temporarily within the context of your application. Since WeakSet elements can be garbage collected, it can help reduce memory usage and avoid memory leaks.

Important Points

  • WeakSet can only contain objects and not primitive values like numbers or strings.
  • WeakSet elements are automatically garbage collected when there are no more references to them.
  • WeakSet does not have an iterator method, so you cannot loop over its elements directly.

Summary

WeakSet is a data structure introduced in ES6 that allows you to store a collection of unique objects. The main feature of WeakSet is that its elements can be garbage collected if there are no references to them. This feature makes WeakSet useful for storing temporary objects in your application. However, WeakSet can only contain objects and not primitive values, and it does not have an iterator method.

Published on: