• JavaScript Video Tutorials

JavaScript - Map.delete() Method



The Map.delete() method in JavaScript is used to remove/delete a key-value pair from a Map object.

This method accepts a parameter: "key", that represents the key-value pair to be removed from the Map object. When the method is invoked, it checks if the specified key is present within the Map 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 Map object, this method returns "false".

We can use clear() method remove all the key-value pairs in a Map object.

Syntax

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

mapInstance.delete(key)

Parameters

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

  • key − The key of the key-value pair to be deleted from the map.

Return value

This method returns a boolean value as a result.

Examples

Example 1

In the following example, we are removing a key-value pair, whose key is 'a' using the JavaScript Map.delete() method −

<html>
<body>
   <script>
      let map = new Map();
      map.set('a', 'apple');
      document.write(map.delete('a'));
   </script>
</body>
</html>

After executing the above program, it returns "true" because the element "a" existed in the Map object and has been removed.

Example 2

Here, we are trying to remove a Non-Existent Key from the Map object −

<html>
<body>
   <script>
      let map = new Map();
      map.set('a', 'apple');
      document.write(map.delete('b'));
   </script>
</body>
</html>

It returns "false" because the key 'b' is not present in the Map object.

Example 3

If we want to remove multiple key-value pairs from Map object, we need to call delete() method multiple times manually −

<html>
<body>
   <script>
      let map = new Map();
      map.set('a', 'apple');
      map.set('b', 'banana');
      map.set('c', 'cherry');
      document.write("Size of the map (Before deletion): ", map.size, "<br>")
      
      document.write(map.delete('a'), "<br>");
      document.write(map.delete('b'), "<br>");
      
      document.write("Size of the map (After deletion): ", map.size)
   </script>
</body>
</html>

If we execute the program, it returns "true" and removes 2 key-value pairs from the Map object.

Example 4

If we want to remove all the elements from the Map object, we use the JavaScript clear() method.

<html>
<body>
   <script>
      let map = new Map();
      map.set('a', 'apple');
      map.set('b', 'banana');
      map.set('c', 'cherry');
      document.write("Size of the map (Before deletion): ", map.size, "<br>")      
      map.clear();      
      document.write("Size of the map (After deletion): ", map.size)
   </script>
</body>
</html>

After executing the above program, it removes all the key-value pairs from the Map object.

Advertisements