Understanding Maps In JavaScript

Introduction

 
If you are familiar with other languages such as C#, Java, or C++, JavaScript’s map data-structure is similar to a dictionary (dictionary is the equivalent of JavaScript Map in other programming languages). Knowing the concepts of key/value pair data structures in other languages will help you instantly to grasp the basic concepts here. However, if you haven’t touched any of these languages it won’t hurt because will still start from the basics.
 
Lastly, if you are one of those developers who remain comfortable with objects-as-maps and have decided to see if the JavaScript Map can save your day you are in the right place.
 
Ok, then let’s get started.
 

Prior to JavaScript Maps

 
Before Map was introduced to the JavaScript language object was the primary way for creating a key/value pair data structures. However, the major drawback of using this technique is the inability to use a non-string value as the key. Let’s see an example.
  1. var sqlServer = {};  
  2.    
  3. var firstInstance = { id: 1 };  
  4. var secondInstance = { id: 2 };  
  5.    
  6. sqlServer[firstInstance] = "SQLServer1";  
  7. sqlServer[secondInstance] = "SQLServer2";  
The main idea here is that the two objects firstInstance and secondInstance both resulted into "[object Object]". Thus, only one key was set in sqlServer. Let us see this in action below.
 
Output
 
Understanding Maps In JavaScript
 
Of course, creating your own implementation of clone-maps or reinventing the wheel may cost you more time, especially when complexity enters the picture. However, today we can use the JavaScript-Map object collection to help us deal with key/value pairs.
 

What is a JavaScript Map?

 
Fundamentally, a Map is a collection of key/value pairs. These keys and values are of any data-type.
 

How to Create a Map?

 
It is easy to create a new Map in JavaScript. Let’s see an example.
  1. let myMap = new Map();  
  2. console.log(myMap);  
Output
 
Understanding Maps In JavaScript
 
As you can see, we just created an empty Map. That’s it! Just by using the Map constructor, you can directly create a new Map in JavaScript.
 

How to Initialize Map?

 
How about creating and initializing a new Map with data? There are various ways to initialize it. Let’s see them one by one.
 
Using an Array
  1. //using an array  
  2. let topProgrammingLanguages = new Map([  
  3.     [1, 'JavaScript'],  
  4.     [2, 'Python'],  
  5.     [3, 'Java'],  
  6.     [4, 'C#'],  
  7.     [5, 'C']  
  8. ]);  
  9.    
  10. console.log(topProgrammingLanguages);  
  11. //end of using an array.  
Output
 
Understanding Maps In JavaScript
 
Using The set() Method
  1. //using the set method  
  2. let myFavoriteBooks = new Map();  
  3. myFavoriteBooks.set(1, 'Rich Dad Poor Dad');  
  4. myFavoriteBooks.set(2, 'The Magic of Thinking Big');  
  5. myFavoriteBooks.set(3, 'Think and Grow Rich');  
  6. myFavoriteBooks.set(4, 'How to Win Friends & Influence People');  
  7. myFavoriteBooks.set(5, 'Shoe Dog');  
  8.    
  9. console.log(myFavoriteBooks);  
  10. //end of using set Method  
Output
 
Understanding Maps In JavaScript
 

Using the get, has, includes, clear, and delete Methods

 
Using The get() Method
 
This method returns the associated value of the key and if doesn’t exist returns undefined.
  1. let sqlServerInstances = new Map();  
  2.    
  3. sqlServerInstances.set('SQL_DEV_Instance''MS_SQLSERVER_1');  
  4. sqlServerInstances.set('SQL_UAT_Instance''MS_SQLSERVER_2');  
  5. sqlServerInstances.set('SQL_PROD_Instance''MS_SQLSERVER_3');  
  6.    
  7. console.log(sqlServerInstances.get("SQL_DEV_Instance")); //output: MS_SQLSERVER_1   
  8. console.log(sqlServerInstances.get('SQL_UAT_Instance')); //output: MS_SQLSERVER_2   
  9. console.log(sqlServerInstances.get("SQL_PROD_Instance")); //output: MS_SQLSERVER_3  
Using The has() Method
 
This method checks whether the key exists within the Map
  1. let sqlServerInstances = new Map();  
  2.    
  3. sqlServerInstances.set('SQL_DEV_Instance''MS_SQLSERVER_1');  
  4. sqlServerInstances.set('SQL_UAT_Instance''MS_SQLSERVER_2');  
  5. sqlServerInstances.set('SQL_PROD_Instance''MS_SQLSERVER_3');  
  6.    
  7. console.log(sqlServerInstances.has("SQL_PROD_Instance")) //output: true  
  8. console.log(sqlServerInstances.has("SQL_PROD2_Instance")) //output: false  
Using The clear() Method
 
This method clears the entire Map collection.
  1. let products = new Map();  
  2.    
  3. products.set("PRODUCT_001", { name: "Product 1" });  
  4. products.set("PRODUCT_002", { name: "Product 2" });  
  5. products.set("PRODUCT_003", { name: "Product 3" });  
  6.    
  7. //let's get the size of the Map before invoking clear()  
  8. console.log(products.size); //output: 3  
  9. products.clear(); //clears the Map-products  
  10. console.log(products.size); //output: 0  
Using The delete() Method
 
This method removes the key-value pair inside the Map.
  1. let sqlServerInstances = new Map();  
  2.    
  3. sqlServerInstances.set('SQL_DEV_Instance''MS_SQLSERVER_1');  
  4. sqlServerInstances.set('SQL_UAT_Instance''MS_SQLSERVER_2');  
  5. sqlServerInstances.set('SQL_PROD_Instance''MS_SQLSERVER_3');  
  6.    
  7. //let's delete the UAT instance  
  8. console.log(sqlServerInstances.get('SQL_UAT_Instance')); //output: MS_SQLSERVER_2   
  9. console.log(sqlServerInstances.delete('SQL_UAT_Instance')); //deletes the key/value pair  
  10. console.log(sqlServerInstances.has('SQL_UAT_Instance')); //output: false  
  11. console.log(sqlServerInstances.get('SQL_UAT_Instance')); //output: undefined  

Ways to Iterate over a map

 
In this section, we are going to see how to iterate over a Map. However; before that we need to discuss the following methods: keys, values, and entries. This will all make sense when we start to see how to use these methods when iterating the map using the for-of loop.
 

Using the keys, values, and entries Methods

 
A reminder, the code sample below will be utilized as our source of data.
  1. let myFavoriteBooks = new Map();  
  2. myFavoriteBooks.set(1, 'Rich Dad Poor Dad');  
  3. myFavoriteBooks.set(2, 'The Magic of Thinking Big');  
  4. myFavoriteBooks.set(3, 'Think and Grow Rich');  
  5. myFavoriteBooks.set(4, 'How to Win Friends & Influence People');  
  6. myFavoriteBooks.set(5, 'Shoe Dog');  
Using The keys() Method
 
This method returns the keys for each element in the Map object. Moreover, if you simply need the keys of the Map collection, this a convenient method for that case, especially when iterating through the keys.
  1. const myMap1 = new Map([[1, 'red'], [2, 'blue']]);  
  2. console.log(myMap1.keys()); //output: { 1, 2 }  
Iterate Over keys
  1. //iterate over the keys   
  2. /** 
  3.  * Output 
  4.  * 1 
  5.  * 2 
  6.  * 3 
  7.  * 4 
  8.  * 5 
  9.  */  
  10. for (const key of myFavoriteBooks.keys()) {  
  11.     console.log(key);  
  12. }  
  13. //end of iteration over the keys   
Using The values() Method
 
This method returns the values for each element in the Map object. Moreover, like the keys method which is the exact opposite of this method, that is solely focused on getting the values of the Map collection.
  1. const myMap2 = new Map([['Electronic Gadget''Smart Phone'], ['Input Devices''Mouse']]);  
  2. console.log(myMap2.values()); //output: {"Smart Phone", "Mouse"}  
Iterate Over values
  1. //iterate over the values  
  2. /** 
  3.  * Output 
  4.  * Rich Dad Poor Dad 
  5.  * The Magic of Thinking Big 
  6.  * Think and Grow Rich 
  7.  * How to Win Friends & Influence People 
  8.  * Shoe Dog 
  9.  */  
  10. for (const value of myFavoriteBooks.values()) {  
  11.     console.log(value);  
  12. }  
  13. //end of iteration over the values  
Using The entries() Method
 
This method returns the object that contains the [key, value] pairs for each element in the Map collection. 
  1. const myMap3 = new Map([['Samsung''Smart Phone'], ['Colgate''Toothpaste'], ['Coke''Soda']]);  
  2. console.log(myMap3.entries()); //output: {"Samsung" => "Smart Phone", "Colgate" => "Toothpaste", "Coke" => "Soda"}  
Iterate Over entries
  1. //iterate over the entries  
  2. /** 
  3.  * Output 
  4.  * 1 "Rich Dad Poor Dad" 
  5.  * 2 "The Magic of Thinking Big" 
  6.  * 3 "Think and Grow Rich" 
  7.  * 4 "How to Win Friends & Influence People" 
  8.  * 5 "Shoe Dog" 
  9.  */  
  10. for (const [key, value] of myFavoriteBooks.entries()) {  
  11.     console.log(key, value);  
  12. }  
  13. //end of iteration over the entries   
Spreading a map
 
Now, at last, we are in the last section of our article. Using the spread operator (...), we can easily spread our map like the example below.
  1. let fastFoods = new Map([[1, 'McDO'], [2, 'Burger King'], [3, 'KFC'], [4, 'Wendys'], [5, 'Pizza Hut']]);  
  2.    
  3. console.log(...fastFoods.keys());  
  4. console.log(...fastFoods.values());  
Hopefully, you can guess what are the outputs of the sample code above. If you have read and understood the previous sections of this article, you can guess it. By the way, if you are confident with your answer you can comment on the comment section below. Thanks.
 

Summary

 
In this post, we have tackled the JavaScript Map object collection. We have started with objects-as-maps and have shown their drawbacks and how the Map collection saves the day. Moreover, we have seen the different methods and how to interact with them. Lastly, we have seen how to iterate over a Map collection with the use of for-of loops and spread operator (...).
 
I hope you have enjoyed reading this article, as much I have enjoyed writing it. Stay tuned for more. This article was originally written and posted here. Many thanks, until next time, happy programming!