JavaScript Map get() Method
Last Updated :
22 May, 2023
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:
- key: It is the key of the element of the map which has to be returned.
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.
javascript
let myMap = new Map();
myMap.set(0, 'GeeksforGeeks' );
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.
Javascript
let myMap = new Map();
myMap.set(0, 'GeeksforGeeks' );
myMap.set(1, 'is an online portal' );
myMap.set(2, 'for geeks' );
console.log(myMap.get(0));
console.log(myMap.get(2));
console.log(myMap.get(4));
|
Output:
"GeeksforGeeks"
"for geeks"
undefined
Exceptions:
- If the variable is not of the Map type then the Map.get() operation throws a TypeError.
- If the index specified in the Map.get() function doesn’t belong to the [key, value] pairs of a map, the Map.get() function returns undefined.
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:
- Google Chrome 38.0
- Microsoft Edge 12.0
- Firefox 13.0
- Internet Explorer 11.0
- Opera 25.0
- Safari 8.0
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...