• JavaScript Video Tutorials

JavaScript - Map.has() Method



The Map.has() method in JavaScript is used to verify whether an element with a specified key exists in the Map object.

This method takes a "key" of the element as an argument to test for presence in the Map object and returns a Boolean value as a result. If the specified key is present in the Map, it returns "true". Otherwise, it returns "false".

The Map.has() method will still return "true", if a key exists in the Map and if the corresponding value in the key-value pair is "undefined".

Syntax

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

has(key)

Parameters

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

  • key − The key to check for existence in the Map.

Return value

This method returns Boolean value as a result.

Examples

Example 1

In the following example, we are checking whether an element with the specified key ('a') exists in this Map or not −

<html>
<body>
   <script>
      let map = new Map();
      map.set('a', 'apple');
      map.set('b', 'banana');
      
      document.write(map.has('a')); // Output: true
   </script>
</body>
</html>

The above program returns "true" because the key "a" is present in the Map.

Example 2

Here, we are trying to check an element with a specified key 'b' which is not present in the Map object.

<html>
<body>
   <script>
      let map = new Map();
      map.set('a', 'apple');
      map.set('b', 'banana');
      
      document.write(map.has('b')); // Output: false
   </script>
</body>
</html>

The above program returns "false" because the key "b" is not present in the Map.

Example 3

In this case, map has a key 'a' with a value of undefined −

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

The above program returns true because 'a' exists, even though its value is undefined.

Advertisements