• JavaScript Video Tutorials

JavaScript - WeakMap delete() Method



In JavaScript, the WeakMap.delete() method removes the specified element from a WeakMap.

This method takes a parameter: "key", that represents the key-value pair to be removed from the WeakMap object. When the method is invoked, it checks if the specified key is present within the WeakMap object, if it is found, the corresponding key-value pair will be removed from the Map and returns "true" as result. However, if the specified key is not found in the WeakMap object, this method returns "false".

Syntax

Following is the syntax of JavaScript WeakMap.delete() method −

weakMapInstance.delete(key)

Parameters

This method accepts only one parameter. The same is described below −

  • key − The key of the key-value pair to remove.

Return value

This method returns Boolean value as a result.

Examples

Example 1

In the following example, we are removing a single key-value pair from the WeakMap using the JavaScript WeakMap.delete() method −

<html>
<body>
   <script>
      let weakMap = new WeakMap();
      let key = { id: 1 };
      weakMap.set(key, "apple");
      document.write(weakMap.delete(key), "<br>");
      document.write(weakMap.has(key));
   </script>
</body>
</html>

After deletion, the has() method checks if the key is still present, which returns "false".

Example 2

In this example, the delete() method is called twice to remove two key-value pairs −

<html>
<body>
   <script>
      let weakMap = new WeakMap();
      let key1 = { id: 1 };
      let key2 = { id: 2 };
      weakMap.set(key1, "apple");
      weakMap.set(key2, "banana");
      
      document.write(weakMap.delete(key1), "<br>"); //true
      document.write(weakMap.delete(key2), "<br>"); //true
      
      document.write(weakMap.has(key1), "<br>"); //false
      document.write(weakMap.has(key2)); //false
   </script>
</body>
</html>

After both deletions, the has() method checks if the keys are still present, which returns "false".

Example 3

In the example below, the delete() method is called on a key that does not exist in the WeakMap −

<html>
<body>
   <script>
      let weakMap = new WeakMap();
      let key = { id: 1 };
      document.write(weakMap.delete(key));
   </script>
</body>
</html>

If we execute the above program, it returns false.

Advertisements