JavaScript Map get()
Syntax & Examples

Map.get() method

The get() method of the Map object in JavaScript returns the value associated with the passed key, or undefined if there is none.


Syntax of Map.get()

The syntax of Map.get() method is:

get(key)

This get() method of Map returns the value associated to the passed key, or undefined if there is none.

Parameters

ParameterOptional/RequiredDescription
keyrequiredThe key of the element to retrieve from the Map.

Return Type

Map.get() returns value of type any.



✐ Examples

1 Using get() to retrieve a value from a Map

In JavaScript, we can use the get() method to retrieve the value associated with a specific key in a Map object.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the get() method to retrieve the value associated with the key 'a' in the map.
  3. Log the result to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2]]);
const valueA = map.get('a');
console.log(valueA);

Output

1

2 Using get() to retrieve a non-existent key

In JavaScript, we can use the get() method to try to retrieve a value for a key that is not present in the Map object, which will return undefined.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the get() method to try to retrieve the value associated with the key 'c' in the map.
  3. Log the result to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2]]);
const valueC = map.get('c');
console.log(valueC);

Output

undefined

3 Using get() with a Map of objects

In JavaScript, we can use the get() method to retrieve the value associated with an object key in a Map object.

For example,

  1. Create a new Map object map with initial key-value pairs where keys are objects.
  2. Use the get() method to retrieve the value associated with a specific object key in the map.
  3. Log the result to the console using console.log().

JavaScript Program

const key1 = { id: 1 };
const key2 = { id: 2 };
const map = new Map([
  [key1, 'value1'],
  [key2, 'value2']
]);
const valueKey1 = map.get(key1);
console.log(valueKey1);

Output

value1

Summary

In this JavaScript tutorial, we learned about get() method of Map: the syntax and few working examples with output and detailed explanation for each example.