The get() method of the Map object in JavaScript returns the value associated with the passed key, or undefined if there is none.
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.
Parameter | Optional/Required | Description |
---|---|---|
key | required | The key of the element to retrieve from the Map. |
Map.get() returns value of type any
.
In JavaScript, we can use the get()
method to retrieve the value associated with a specific key in a Map object.
For example,
map
with initial key-value pairs.get()
method to retrieve the value associated with the key 'a' in the map
.console.log()
.const map = new Map([['a', 1], ['b', 2]]);
const valueA = map.get('a');
console.log(valueA);
1
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,
map
with initial key-value pairs.get()
method to try to retrieve the value associated with the key 'c' in the map
.console.log()
.const map = new Map([['a', 1], ['b', 2]]);
const valueC = map.get('c');
console.log(valueC);
undefined
In JavaScript, we can use the get()
method to retrieve the value associated with an object key in a Map object.
For example,
map
with initial key-value pairs where keys are objects.get()
method to retrieve the value associated with a specific object key in the map
.console.log()
.const key1 = { id: 1 };
const key2 = { id: 2 };
const map = new Map([
[key1, 'value1'],
[key2, 'value2']
]);
const valueKey1 = map.get(key1);
console.log(valueKey1);
value1
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.