Computer >> Computer tutorials >  >> Programming >> Javascript

WeakMap object in JavaScript.


The WeakMap object has key-value pair as elements where the key should be an object and the value can be any primitive value or object. The objects which are used as keys in a WeakMap are garbage collected if they don’t have any reference to them.

Following is the code for WeakMap object in JavaScript −

Example

<!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: rebeccapurple;
   }
</style>
</head>
<body>
<h1>WeakMap object in JavaScript</h1>
<div class="result"></div>
<button class="Btn">Show WeakMap</button>
<h3>Click on the above button to create and display a WeakMap object</h3>
<button class="Btn">REMOVE</button>
<h3>Click on the above button to remove reference of the WeakMap key</h3>
<script>
   let resultEle = document.querySelector(".result");
   let btnEle = document.querySelectorAll(".Btn");
   let personObj = {
      name: "Rohan Sharma",
      age: 22,
      class: 9,
   };
   let WeakMap1 = new WeakMap();
   WeakMap1.set(personObj, "Rohan Object");
   btnEle[0].addEventListener("click", () => {
      resultEle.innerHTML = "personObj : " + WeakMap1.get(personObj) + "<br>";
   });
   btnEle[1].addEventListener("click", () => {
      personObj = null;
      resultEle.innerHTML += "personObj : " + WeakMap1.get(personObj) + "<br>";
      resultEle.innerHTML += " personObj is now removed from memory";
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

WeakMap object in JavaScript.

On clicking the ‘Show WeakMap’ button −

WeakMap object in JavaScript.

On clicking the ‘REMOVE’ button −

WeakMap object in JavaScript.