1
6

JavaScript: How to create and use JavaScript Map

Reading Time: 2 minutes

We can create JavaScript Map whenever there is a need to store key-value pairs, it is a built-in object since ES6 that can allow storage and retrieval of objects easily. Here, let’s explore how to use this built-in object.

Advantages of using a Map

There are several advantages in using Map. Here are some of them.

  • No duplication. For any key, there is only 1 value
  • Allow setting any data type as keys and values
  • Remember insertion order
  • Easy access to value when key is known

Various Key DataType Supported

  • Primitive
  • Function
  • Objects

How to create and use JavaScript Map

Pre ES6 Style

Prior to ES6, we can create a Map by using a 2-dimensional array. However, this method makes the code complicated to handle like insertion and deletion operation. Below shows the illustration of creating and iterating a Map prior to ES6.

// Create a array map to iterate over
var ageMap = [
  ['Person1', 11],
  ['Person2', 33],
  ['Person3', 44], 
  ['Person4', 66],
  [10000001, 11]
];

// Iterating 2D array
for (var i in ageMap){
  for (var m = 0; m < ageMap[i].length; m++){
    console.log(ageMap[i][m]);  
  }
}

ES6 Style

With the introduction of Map datatype, it has become easier for developer to perform operation like create, insert and delete on Map.

In the below illustration, we will show how to create and store 3 person age into a map. Also, how to delete and retrieve them.

const ageMap = new Map();

// Set age via string type key
ageMap.set('person1', 41);
ageMap.set('person2', 31);
ageMap.set('person3', 16);

// Set age via number type key
ageMap.set(100, 19);

// Set age via boolean type key
ageMap.set(true, 18);

// Access age via key
console.log(ageMap.get('person1'));  // 41

// Delete age via key
ageMap.delete('person1');

// Check how many key-value pair are in the Map
console.log(ageMap.size);  // 4

Related Operation on Map

There are also other useful operations that we have discuss in this blog.

Conclusion

Although there are other common data structure like array, JavaScript Map is much more easy to use with key without the need to iterate over the whole Map.

For other examples, can refer to MDN documentation here.

Show Comments

No Responses Yet

Leave a Reply