Open In App

JavaScript Map get() Method

The Map.get() method in JavaScript is used for returning a specific element among all the elements which are present in a map. The Map.get() method takes the key of the element to be returned as an argument and returns the element which is associated with the specified key passed as an argument. If the key passed as an argument is not present in the map, then Map.get() method returns undefined. The Map.get() method is used to get a specific element among all the elements which are present in a map.

Syntax:



mapObj.get(key)

Parameter Value:

Return Value: The Map.get() method returns the element which is associated with the specified key passed as an argument or undefined if the key passed as an argument is not present in the map.



The examples below illustrate the get() method:

Example 1: This example describes the Map() method to create the map object that contains the [key, value] pair to the map & displays the element that is associated with the specific key using the Map.get() method.




// Creating a map object
let myMap = new Map();
 
// Adding [key, value] pair to the map
myMap.set(0, 'GeeksforGeeks');
 
// Displaying the element which is associated with
// the key '0' using Map.get() method
console.log(myMap.get(0));

Output:

"GeeksforGeeks"

Example 2: This example describes the Map() method to create the map object that contains the multiple [key, value] pair to the map & displays the element that is associated with the specific key using the Map.get() method.




// Creating a map object
let 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 the elements which are
//associated with the keys '0', '2'
// and '4' using Map.get() method
console.log(myMap.get(0));
console.log(myMap.get(2));
console.log(myMap.get(4));

Output:

"GeeksforGeeks"
"for geeks"
undefined

Exceptions:

To see the difference between the Javascript Map and Objects, go through this Map vs Object In Javascript article.

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

Supported Browsers:


Article Tags :