JavaScript WeakSet


The JavaScript WeakSet is used for storing collection of objects. Like set it doesn’t store duplicates.

Methods of WeakSet −

MethodDescription
add(obj)Append new value to the weakSet.
delete(obj)Deletes the value from weakSet.
has(obj)Returns true or false depending upon if the weakSet object contains the value or not.
length()Returns the weakSet object length

Following is the code for the WeakSet in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>JavaScript WeakSet</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
CLICK the above button to add obj1 and obj2 to the WeakSet object
</h3>
<script>
   let resultEle = document.querySelector(".result");
   let weakObj = new WeakSet();
   let obj1 = { a: 22 };
   let obj2 = { b: 44 };
   document.querySelector(".Btn").addEventListener("click", () => {
      weakObj.add(obj1);
      resultEle.innerHTML += "Obj1 added to weakset <br>";
      weakObj.add(obj2);
      resultEle.innerHTML += " Obj2 added to weakset <br>";
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −

Updated on: 12-May-2020

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements