JavaScript WeakSet Tutorial

In this section, we will learn what the WeakSet object is and how to use it in JavaScript.

Note: we’re assuming you’re already familiar with the `Set` constructor function.

What is WeakSet in JavaScript?

The `WeakSet` is a constructor function that creates Set objects just like the `Set` constructor function.

But the main difference is that we cannot use values of primitive types in a `WeakSet` object.

Basically, only values of type `object` are allowed to be used in a `WeakSet` object.

How to Create WeakSet in JavaScript?

Before we get into more details, first let’s see an example of how to create a `WeakSet` object:

Example:

const obj1 ={
    firstName:"John"
  }
  const obj2 = {
    firstName: "Jack"
  }
  const obj3 = {
    firstName : "Omid"
  }
  const weakCollection = new WeakSet();
  weakCollection.add(obj1);
  weakCollection.add(obj2);
  weakCollection.add(obj3);
  console.log(weakCollection);

Output:

WeakSet {{…}, {…}, {…}}
[[Entries]]
0:
value: {firstName: "Jack"}
1:
value: {firstName: "John"}
2:
value: {firstName: "Omid"}
__proto__: WeakSet

Here, we used the `WeakSet` constructor function to create an object.

After that, via the `add()` method, we’ve added 3 elements to the `WeakSet` object. As you can see, the values for all of them is of type Object.

At the end we used the `console.log()` statement and sent the content of the `Set` object to the browser’s console.

Why JavaScript WeakSet object?

Part of the work of the JavaScript engine is to remove those objects in the Heap area of the memory that don’t have any reference to them. The program that does this work is called the garbage collector.

Note: If you don’t know what the Heap area is and also don’t know about referencing an object:

So essentially, as long as there’s a variable referencing an object, that object won’t be garbage collected.

When we pass an object as the element of a `Set` object, that object will stay as a value in the `Set` and won’t be garbage collected.

But this is not true for a WeakSet object.

The `WeakSet` contains weak values. When there’s no reference to the values except in the `WeakSet` object, values are candidates for garbage collection. We use the `WeakSet` when we want to maintain a cache of values and we don’t mind if our values are removed from the Set by the garbage collector.

So in short, if we set an object as the value in a WeakSet object, that value will stay in the set as long as there’s a variable (or property) somewhere in the program is referring to the same object as well.

But, when the object is only referred via the value in the `WeakSet` object, the garbage collector has the right to remove the object from the memory.

Example: creating WeakSet in JavaScript

let obj1 ={
    firstName:"John"
  }
  let obj2 = {
    firstName: "Jack"
  }
  let obj3 = {
    firstName : "Omid"
  }
  let weakCollection = new WeakSet();
  weakCollection.add(obj1);
  weakCollection.add(obj2);
  weakCollection.add(obj3);
  
  obj1 = null;
  obj2 = null;
  obj3 = null;
  
  setTimeout(()=>console.log(weakCollection),10000);

Output:

WeakSet {}
[[Entries]]
No properties
__proto__: WeakSet

Here, we refactored the example at the beginning of this section.

The values that were used in the weak set are also referenced by the `obj1`, `obj2`, and `obj3` variables, respectively.

However, by the time the execution engine executes the three statements below:

obj1 = null;

obj2 = null;

obj3 = null;

Besides the weakest, no external variables or properties are referring to the objects that are used as the values of the set.

At this point, the garbage collector sees the opportunity to remove the objects from the memory.

For this reason, when the last statement ran (after 10 seconds), the content of the target `Set` object was empty.

Notes:

  • The garbage collector won’t run immediately, but it runs periodically once in a while. So it might take a couple of seconds to run and remove those unwanted objects.
  • In the last statement, we used the `setTimeOut()` function to run a statement at 10 seconds later. In the setTimeout() section, we’ve explained how this function works.

JavaScript WeakSet Methods

The `WeakSet` constructor has only these methods:

  • add(key, value)
  • delete(key)
  • has(key)

These methods work exactly the same as their counterpart in the Set object.

Note: the other methods that exist in the `Set` constructor-function, don’t exist in the `WeakSet`.

Example: using WeakSet has() Method in JavaScript

let obj1 ={
    firstName:"John"
  }
  let obj2 = {
    firstName: "Jack"
  }
  let obj3 = {
    firstName : "Omid"
  }
  let weakCollection = new WeakSet();
  weakCollection.add(obj1);
  weakCollection.add(obj2);
  weakCollection.add(obj3);
  
  console.log(weakCollection.has(obj1));
  console.log(weakCollection.has({}));
  console.log(weakCollection.has(obj3));

Output:

true

false

true
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies