JavaScript WeakSet Data Structure

JavaScript WeakSet Data Structure

In this article, I am going to discuss JavaScript WeakSet Data Structure in detail. Please read our previous article where we discussed JavaScript Set with Examples. JavaScript ECMAScript6 (ES6) introduces four new data structures: Set, WeakSet, Map, and WeakMap. Let’s start exploring and understanding in detail more about WeakSet. At the end of this article, you will understand the following pointers.

  1. What is WeakSet in JavaScript?
  2. Where to use WeakSet Data Structure in JavaScript?
  3. Features of WeakSet Data Structure
  4. JavaScript WeakSet Methods
  5. How to Create a WeakSet in JavaScript?
  6. How to Add a Value to a WeakSet?
  7. Removing a value from a WeakSet
  8. Checking if a value exists in a WeakSet
  9. Set Vs WeakSet in JavaScript
  10. JavaScript Weakset garbage collector
What is WeakSet in JavaScript?

A WeakSet is the same as a Set except that it contains only objects. (objects are nothing but a data structure that allows us to store any kind of value. Will learn more about this in the object chapter. WeakSet is a collection of unique objects only. Same as like Sets, each object in a WeakSet may appear only once; all objects are unique in a WeakSet’s collection.

The WeakSet object is used for storing weakly held objects in a WeakSet. The WeakSet is different from Set as we can’t store primitive values (like numbers or string) in it. The reason why objects are allowed as values or key is that because primitive values are never garbage-collected. Hence if we try to use primitive value, it will throw a type error TypeError: Invalid value used in weak set.

As the name implies the WeakSet is they are weak, meaning references to the objects in the WeakSet are held weakly, which means that if there is no other reference to an object stored in a WeakSet, it can be garbage collected means the garbage collector will collect and free the memory of those object which has occupied the memory and are not currently in use in any of our program or code.

Garbage collection in JavaScript is performed automatically by JS Engine so the developer did not need to be concern about it.

Since objects in a WeakSet are automatically garbage-collected due to having a weak reference, WeakSet collection doesn’t contain iterable or the method that can return the list of keys. We can access the size of WeakSet. Hence WeakSet does not have a size property and we cannot determine its size.

Where to use WeakSet Data Structure in JavaScript?

We only use a WeakSet to check if a specified value is in the set or not. It is useful for a metadata table (info about table) indicating whether a reference is actively in use or not.

Features of WeakSet Data Structure:
  1. WeakSet – is a collection of unique objects only.
  2. In WeakSet, if there is no reference to a stored object, they are automatically clean up by a garbage collector.
  3. In WeakSet, the objects are not iterable or enumerable. WeakSet can’t be iterated.
  4. As WeakSet object cannot be iterable hence it doesn’t have a size property.
Syntax:

The below syntax creates new WeakSet

new WeakSet([iterable]); The WeakSet constructor also accepts an optional iterable object

iterable: If we provide an iterable object (usually as an array) to the WeakSet constructor, all the elements of the iterable object will be added to the new WeakSet. null is treated as undefined.

JavaScript WeakSet Methods

The WeakSet object has three methods, all of them work the same as the Set methods:

JavaScript WeakSet Methods

Creating a WeakSet in JavaScript

The WeakSet constructor has an optional parameter/argument, which can be any type of iterable object (for example an array). All the elements of the iterable object will be added to the newly created WeakSet.

const object1 = {}, object2 = {};
const weakset = new WeakSet([object1, object2]);

Example: JavaScript WeakSet example
<html>
<head>
    <title>JavaScript WeakSet example</title>
</head>
<body>
    <script>
        let season = { type: 'winter' };
        let temperature = { type: 'low' };
        let myWeakSet = new WeakSet([season, temperature]);

        console.log("WeakSet example:", myWeakSet);
        console.log("type of myWeakSet:", typeof (myWeakSet));
        let result = myWeakSet instanceof WeakSet;
        console.log("check if myWeakSet instance of WeakSet:", result);
    </script>
</body>
</html>

Output:

JavaScript WeakSet Data Structure Example

Example: JavaScript Weakset garbage collector example
<html>
<head>
    <title>JavaScript WeakSet garbage collector example</title>
</head>
<body>
    <script>
        let myWeakSet = new WeakSet();
        let obj = {};
        myWeakSet.add(obj);
        console.log(myWeakSet.has(obj));

        // break the last reference to the object we created earlier
        obj = 50;

        // false because no other references to the object which the weakset points to
        // because weakset was the only object holding a reference it released it and got garbage collected
        console.log(myWeakSet.has(obj));
    </script>
</body>
</html>

Output:

JavaScript Weakset garbage collector example

In the above example, to see if a weakset still has a reference to certain objects or not for that we have use weakset.has() method. As the name implies this method returns a boolean value indicating whether the object still there in weakset or not.

Adding a Value to a WeakSet

To add a value to a WeakSet, use the add() method. This add() method is chainable. To add a value to a WeakSet, use the add() method:

myWeakSet.add(value);

chainable add() method

myWeakSet.add(season).add(temperature).add(obj1);

Example: JavaScript WeakSet add() method example
<html>
<head>
    <title>JavaScript WeakSet add() method example</title>
</head>
<body>
    <script>
        let season = { type: 'winter' };
        let temperature = { type: 'low' };
        let numbers = [1, 2, 3];
        let obj1 = {}; //empty object
        let obj2 = {};

        let myWeakSet = new WeakSet();
        myWeakSet.add(season);
        myWeakSet.add(temperature);
        myWeakSet.add(numbers);
        myWeakSet.add(new Date());
        myWeakSet.add(obj1)
            .add(obj2)
            .add(obj1)
            .add(obj2);

        console.log("WeakSet after adding a value:", myWeakSet);//add unique object no duplicates

        try {
            myWeakSet.add(true);//primitive value(int, string and boolean)not allowed
        } catch (error) {
            console.log(error);
        }
    </script>
</body>
</html>

Output:

JavaScript WeakSet Data Structure add() method example

As we can see from the above example, though we have added 8 elements in the WeakSet, it showing 6 elements in the output as it has removed the duplicate objects because of having a feature of storing unique objects also it shows that WeakSet doesn’t allow primitive value to be stored.

Removing a value from a WeakSet

Deleting an element from a WeakSet is as simple as calling the delete() method, and passing in the element we want to remove. To remove a value from a WeakSet, use the delete() method.

myWeakSet.delete(value); This method will return true if the value existed in the WeakSet and has been removed, otherwise false.

Example: JavaScript WeakSet delete() method example
<html>
<head>
    <title>JavaScript WeakSet delete() method example</title>
</head>
<body>
    <script>
        let season = { type: 'winter' };
        let temperature = { type: 'low' };
        let obj1 = {}; //empty object
        let obj2 = {};

        let myWeakSet = new WeakSet();
        myWeakSet.add(season);
        myWeakSet.add(temperature);
        myWeakSet.add(obj1);

        console.log("WeakSet after adding a value:", myWeakSet);//count:3
        console.log("Does Weakset has season element?", myWeakSet.has(season));
        console.log("Weakset deleting an existing value(season):", myWeakSet.delete(season));
        console.log("Does Weakset has obj2 element?", myWeakSet.has(obj2));
        console.log("Weakset deleting an non-existing value(obj2):", myWeakSet.delete(obj2));//obj2 is not added into WeakSet hence returning false
        console.log("Weakset after deleting a value:", myWeakSet);//count:2
    </script>
</body>
</html>

Output:

JavaScript WeakSet delete() method example

Checking if a value exists in a WeakSet

When we want to check if a WeakSet contains an element, call the has() method on it. It returns a Boolean value(true/false) whether an element is present with the given value in the WeakSet object or not. To check if a given value exists in a WeakSet, use has() method:

myWeakSet.has(value); Will return true if the value appears in the WeakSet, false otherwise.

Example: JavaScript WeakSet has() method example
<html>
<head>
    <title>JavaScript WeakSet has() method example</title>
</head>
<body>
    <script>
        let season = { type: 'winter' };
        let temperature = { type: 'low' };
        let obj1 = {}; //empty object
        let obj2 = {};

        let myWeakSet = new WeakSet();
        myWeakSet.add(season);
        myWeakSet.add(temperature);
        myWeakSet.add(obj1);

        console.log("Check if myWeakSet contains obj1:", myWeakSet.has(obj1));
        console.log("Check if myWeakSet contains obj2:", myWeakSet.has(obj2));
    </script>
</body>
</html>

Output:

JavaScript WeakSet has() method example

Set Vs WeakSet in JavaScript

Set Vs WeakSet in JavaScript

In the next article, I am going to discuss the JavaScript Map Data Structure with Examples. Here, in this article, I try to explain the JavaScript WeakSet Data Structure with examples. I hope this JavaScript WeakSet Data Structure article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this JavaScript WeakSet Data Structure article.

Leave a Reply

Your email address will not be published. Required fields are marked *