• JavaScript Video Tutorials

JavaScript - The Maps Object



A Map object in JavaScript is a collection of key-value pairs where the keys can be of any type, including objects or functions. The order of the map elements is the same as the insertion order of the key-value pairs.

To create a new Map object, you can use the new Map() constructor. You can then add key-value pairs to the map using the set() method. To get the value for a particular key, you can use the get() method. To remove a key-value pair from the map, you can use the delete() method.

Syntax

Following is the syntax to use the Map data structure in JavaScript −

const map = new Map([iterable]);

In the above syntax, we used the 'new' keyword with a Map() constructor to define an instance of the Map.

Parameters

  • iterable − It is an iterable containing the key-value pairs to initialize the map with elements of the iterable. Also, it is an optional parameter.

The Map class in JavaScript contains a set of built-in methods that allow us to work with Map objects. Here, we have listed the properties and methods of the Map.

Map Properties

Following are the properties of Map object −

Sr.No. Name & Description
1

size

This property returns the number of elements in this map.

Map Methods

In the following table, we have listed all the methods of Map object and their description −

Sr.No. Name & Description
1

clear()

This method removes all elements from a Map object.

2

delete()

This method removes a specified element from a Map object by key.

3

entries()

This method returns a new map iterator object that contains the [key, value] pairs.

4

forEach()

This method executes a callback function once per each key/value pair in a Map object.

5

get()

This method is used to return a specified element from a Map object.

6

has()

This method indicates whether an element with the specified key exists or not.

7

keys()

This method returns a new Iterator object that contains the keys for each element in the Map object.

8

set()

This method insert the key-value pair to a Map object.

9

values()

This method returns a new Iterator object that containing values of the Map object.

JavaScript Map Constructor()

Following is the constructor of Map in JavaScript −

Sr.No. Name & Description
1

Map()

To create a Map object.

Examples

Example: Creating new Map Object

In the example below, we have passed the 2D array containing the key-value pairs as an argument of the Map() constructor.

After that, we traverse the map to get each value of the map and show in the output.

<html>
<body>
   <div> Map elements are: </div>
   <div id = "output"> </div>
   <script>
      const map = new Map([["Apple", 100], ["Banana", 20], ["Orange", 50]]);
      for (let [key, value] of map) {
         document.getElementById("output").innerHTML += `${key} : ${value} <br>`;
      }
   </script>
</body>
</html>

Output

After executing the above program, it returns each value of the map.

Map elements are:
Apple : 100
Banana : 20
Orange : 50

Example: Inserting key-value pair in the Map

In the example below, we use the set() method to insert the key-value pair in the map. The set() method takes the key as the first argument and the value as the second argument.

<html>
<body>
   <div>After inserting 2 key-value pairs in the map: </div>
   <div id = "output"> </div>
   <script>
      const map = new Map();
      map.set("Grapes", 40);
      map.set("Apples", 50);
      for (let [key, value] of map) {
         document.getElementById("output").innerHTML += `${key} : ${value} <br>`;
      }
   </script>
</body>
</html>

Output

After inserting 2 key-value pairs in the map:
Grapes : 40
Apples : 50

As we can see in the output, the provided [key-value] pairs have been inserted in the Map object.

Example: Accessing Map Elements

The get() method can be used to access the map elements. Here, we have added elements to the set.

After that, we used the get() method to access the values of the name and RollId keys.

<html>
<body>
   <div id = "output1">Name: </div>
   <div id = "output2">Roll Id: </div>
   <script>
      const map = new Map();
      map.set("name", "John");
      map.set("rollId", 123);
      document.getElementById("output1").innerHTML += map.get("name");
      document.getElementById("output2").innerHTML += map.get("rollId");
   </script>
</body>
</html>

Output

After executing, it returns all the elements present in the Map object.

Name: John
Roll Id: 123

Example: Removing a Map Element

In the example below, we use the delete() method to delete the key-value pair having a key 20.

However, you can also use the clear() method to remove all elements from the map.

<html>
<body>
   <div>Map after deleting the [20,30] key-value pair: </div>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      const map = new Map([[10, 20], [20, 30], [30, 40]]);

      map.delete(20); // Deleting a [20,30] key-value pair from the map

      for (let [key, value] of map)
         output.innerHTML += "Key: " + key + " Value: " + value + "<br/>";
   </script>
</body>
</html>

Output

Map after deleting the [20,30] key-value pair:
Key: 10 Value: 20
Key: 30 Value: 40

Example: Size of the Map

In the below code, we used the 'size' property of the Map class to get the total number of key-value pairs in the map.

<html>
<body>
   <p id = "output">Size of the map object is: </p>
   <script>
      const map = new Map();
      map.set("Grapes", 40);
      map.set("Apples", 50);
      document.getElementById("output").innerHTML += map.size;
   </script>
</body>
</html>

Output

Size of the map object is: 2

Example: Use object as a key

The map allows developers to use the object as a key. Here, we have defined the laptop object containing two properties.

After that, we set the object as a key and the laptop's price as a value in the map.

<html>
<body>
   <p id = "output">The laptop price is: </p>
   <script>
      const map = new Map();
      const laptop = {
         brand: "HP",
         model: "Pavilion",
      }
      map.set(laptop, 100000);
      document.getElementById("output").innerHTML += map.get(laptop);
   </script>
</body>
</html>

Output

The laptop price is: 100000

Map vs. Object in JavaScript

A Map is similar to the Object in JavaScript, but there are some differences which we have explained here −

Basis of Comparison Map Object
Keys The map allows you to set the object, function, and other primitive values as a key. The Object can contain only a string and a symbol as a key.
Size You can get the size of the map using the 'size' property. You need to traverse through the object to determine the size of the object.
Key comparison It uses flexible methods to compare the keys. It considers two similar objects with different references different. It implicitly converts the keys into the string and matches them.
Iteration You can use the for...of loop to traverse the map. You can use the for...in loop to traverse the object properties.
Performance The map is slightly slower due to its complex structure. The object is faster than the map as it only stores keys in the string format.
Use cases The map is the better option to use for adding key-value pairs dynamically. The object is better to use if key-value pairs are static and fixed.
Advertisements