Map.get()

The Map.get() method in JavaScript retrieves the value associated with a specific key from a Map object. If the key does not exist, it returns undefined.

Syntax

</>
Copy
map.get(key)

Parameters

ParameterDescription
keyThe key whose associated value is to be retrieved from the Map object.

Return Value

The method returns the value associated with the specified key. If the key does not exist in the Map, it returns undefined.


Examples

1. Retrieving a Value from a Map

This example demonstrates how to retrieve values using the get() method.

</>
Copy
const myMap = new Map();
myMap.set("name", "Arjun");
myMap.set("age", 25);

console.log(myMap.get("name"));
console.log(myMap.get("age"));

Output

Arjun
25
  1. myMap.get("name") returns the value associated with the key "name" which is Arjun.
  2. myMap.get("age") returns the value associated with the key "age" which is 25.

2. Retrieving a Value from a Non-Existent Key

If the key does not exist in the Map, the get() method returns undefined.

</>
Copy
const myMap = new Map();
myMap.set("color", "blue");

console.log(myMap.get("size"));

Output

undefined

3. Using Objects as Keys

The get() method works with objects as keys.

</>
Copy
const objKey = { id: 1 };
const myMap = new Map();

myMap.set(objKey, "Apple");

console.log(myMap.get(objKey));

Output

Apple

The object objKey is used as a key, and its associated value is retrieved successfully.

4. Differentiating Keys by Reference

Keys in a Map are compared by reference, not by value.

</>
Copy
const myMap = new Map();
const key1 = { id: 1 };
const key2 = { id: 1 };

myMap.set(key1, "Apple");

console.log(myMap.get(key1));
console.log(myMap.get(key2));

Output

Apple
undefined

Even though key1 and key2 have the same properties, they are different objects in memory. Only key1 exists in the Map, so myMap.get(key2) returns undefined.