Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript Map.has() Method

Improve Article
Save Article
Like Article
  • Last Updated : 21 Dec, 2022
Improve Article
Save Article
Like Article

The Javascript Map.has() method in JavaScript is used to check whether an element with a specified key exists in a map or not. It returns a boolean value indicating the presence or absence of an element with a specified key in a map. The Map.has() method takes the key of the element to be searched as an argument and returns a boolean value. It returns true if the element exists in the map else it returns false if the element doesn’t exist.

Syntax:

mapObj.has(key)

Parameters Used:

  • key: It is the key of the element of the map which has to be searched.

Return Value: The Map.has() method returns a boolean value. It returns true if the element exists in the map else it returns false if the element doesn’t exist.

Examples of the above function are provided below. 

Example 1: In this example, a map object “myMap” has been created with a single [key, value] pair, and the Map.has() method is used to check whether an element with the key ‘0’ exists in the map or not.

javascript




<script>
    // creating a map object
    var myMap = new Map();
      
    // Adding [key, value] pair to the map
    myMap.set(0, 'geeksforgeeks');
      
    // displaying whether an element with 
    // the key '0' exists in the map or not
    // using Map.has() method
    console.log(myMap.has(0));
</script>

Output:

true

Example 2: In this example, a map object “myMap” has been created with three [key, value] pairs, and the Map.has() method is used to check whether an element with the key ‘0’ and ‘3’ exists in the map or not.

javascript




<script>
    // creating a map object
    var myMap = new Map();
      
    // Adding [key, value] pair to the map
    myMap.set(0, 'geeksforgeeks');
    myMap.set(1, 'is an online portal');
    myMap.set(2, 'for geeks');
      
    // displaying whether an element with the
    // key '0' and '3' exists in
    // the map or not using Map.has() method
    console.log(myMap.has(0));
    console.log(myMap.has(3));
</script>

Output:

true
false

We have a complete list of Javascript Map methods, to check those please go through this JavaScript MapComplete Reference article.

Supported Browsers: 

  • Chrome 38 and above
  • Edge 12 and above
  • Firefox 13 and above
  • Internet Explorer 11 and above
  • Opera 25 and above
  • Safari 8 and above

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!