What is the use of Map in JavaScript?


Map

Map holds key value pairs and remembers the actual insertion order of the keys. Map allows to store only a unique value.

syntax

new Map([iterable])

Case-1: Absence Of Map

In the absence of Map, since javascript object endorses only one key object, If we provide multiple keys only the last one will be remembered. In the following example despite providing many keys such as a and b only b is remembered and displayed as output.So to eliminate this drawback "Map" came in to existence in javascript.

Example

Live Demo

<html>
<body>
<script>
   const x = {};
   const a = {};
   const b = {
      num:3
   }
   x[a] = "a";
   x[b] = "b";
   document.write(JSON.stringify(x));
</script>
</body>
</html>

Output

{"[object Object]":"b"}

case-2: Presence Of Map

As we know from the definition that Map is going to remember the actual insertion order of keys it displays all the key and value pair such as '{}' as a key and 'a' has a value etc. as shown in the output.

Example

Live Demo

<html>
<body>
<script>
   const a = {};
   const b = {
      num:3
   }
   const map = new Map();
   map.set(a, "a").set(b, "b");
   for(let[key, value] of map.entries()){
   document.write(JSON.stringify(key, value)); // displaying key using Map
   document.write((key, value));               // displaying value using Map
}
</script>
</body>
</html>

Output

{}a {"num":3}b

Updated on: 30-Jul-2019

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements