What is WeakSet Object in JavaScript?



In this article, we are going to explore WeakSet objects and how to use them in JavaScript. The JavaScript WeakSet object is a type of collection that allows the user to store items that are held loosely only.

  • WeakSet is just a collection of items that do not include any arbitrary values.

  • It has the same feature as that of a set and does not contain any duplicates.

  • The main difference between the WeakSet and a Set is that a WeakSet is a collection of Objects rather than values of a certain type.

  • It supports the following functions: add, has, delete.

Syntax

new WeakSet([iterable])

Parameter

  • iterable − This is an iterable object which will hold the elements that need to be added to the set.

Advantages of using a WeakSet Object

  • The contents of a weak set are garbage collected.

  • It lowers the memory utilization when properly used.

  • It is very useful for class branding.

Features of a WeakSet Object

  • It consists of unique elements only.

  • Elements will automatically be garbage collected if no references are stored in the weak set.

  • Items in a weak set are not enumerable.

  • It supports the add, has, and delete functions like a set, but does not support size, keys, and iterations function.

WeakSet Methods

  • add()  This method adds/appends values to the weak set.

  • has(value) −This method checks if the weak set has/contains the passed value or not.

  • delete(value) − This method removes a value from the WeakSet.

Example 1

In this example, we are going to use the methods from the weak set and see how to use it in various cases.

#Filename: index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>WeakSet</title>
</head>
<body>
   <script>
      const welcome = {"key": "value"};
      const tutorialspoint = {"title": "tutorialspoint"}
      const weak_set = new WeakSet([welcome, tutorialspoint]);
      
      // Checking if tutorialspoint exists
      document.write("Is tutorialspoint exists: " + weak_set.has(tutorialspoint));
   </script>
</body>
</html>

Output

It will produce the following output.

Is tutorialspoint exists: true

Example 2

#Filename: index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>WeakSet</title>
</head>
<body>
   <script>
      const weak_set = new WeakSet();
      const welcome = {"key": "value"};
      const tutorialspoint = {"title": "tutorialspoint"}
      
      //Adding object to weakset
      weak_set.add(welcome);
      weak_set.add(tutorialspoint);
      
      // Deleteing an object
      weak_set.delete(tutorialspoint);
      document.write("Is tutorialspoint exists: " + weak_set.has(tutorialspoint));
   </script>
</body>
</html>

Output

It will produce the following output.

Is tutorialspoint exists: false

Advertisements