Skip to content

JavaScript Map get() | Method

  • by

JavaScript Map get() method is used to get the value from the map object using a key. This method returns the value of the specified key of an element from a Map object.

obj.get(key)  

Note: It returns undefined if the key can’t be found in the Map object.

JavaScript Map get()

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script >
    var map = new Map();  
    map.set(1,"ABC");  
    map.set(2,"XYZ");  
    map.set(3,"PQR");  

    console.log(map.get(1));  
    console.log(map.get(2)); 
    console.log(map.get(3)); 
    
  </script>
</body>
</html>

Output:

JavaScript Map get() Method

More example

const map1 = new Map();
map1.set('bar', 'foo');

console.log(map1.get('bar'));// "foo"

console.log(map1.get('baz')); // undefined

Using get() to retrieve a reference to an object

const arr = [];
const myMap = new Map();
myMap.set('bar', arr);

myMap.get('bar').push('foo');

console.log(arr); // ["foo"]
console.log(myMap.get('bar')); // ["foo"]

Do comment if you have any doubts or suggestions on this JS map method tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading