Open In App

JavaScript Map get() Method

Last Updated : 17 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Map.get() method in JavaScript is a convenient way to retrieve the value associated with a specific key in a Map object. A Map in JavaScript allows you to store key-value pairs where keys can be of any data type, making it more useful compared to objects, which only allow strings and symbols as keys.

Understanding the Map.get() Method

The Map.get() method takes a single argument—the key of the element you want to retrieve—and returns the value associated with that key. If the key does not exist in the map, the method returns undefined.

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.

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
// 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.

JavaScript
// 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:

  • 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.

Supported Browsers:

  • Google Chrome
  • Microsoft Edge
  • Firefox
  • Opera
  • Safari

Next Article

Similar Reads