Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Understanding Maps in JavaScript

4.70/5 (11 votes)
1 Sep 2020CPOL4 min read 6.2K  
JavaScript Map object collection
In this post, we will take a look at objects-as-maps and show their drawbacks and how the Map collection saves the day. We will see the different methods and how to interact with them, and finally, we will see how to iterate over a Map collection with the use of for-of loops and spread operator.

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 we will still start from the basics.

Lastly, if you are one of those developers who remain comfortable with objects-as-maps and decided to see if the JavaScript Map can save your day, you are reading the right article.

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.

JavaScript
var sqlServer = {};

var firstInstance = { id: 1 };
var secondInstance = { id: 2 };

sqlServer[firstInstance] = "SQLServer1";
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

Image 1

Of course, creating your own implementation of clone-maps or reinventing the wheel may cause 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.

JavaScript
let myMap = new Map();
console.log(myMap);

Output

Image 2

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

JavaScript
//using an array
let topProgrammingLanguages = new Map([
    [1, 'JavaScript'],
    [2, 'Python'],
    [3, 'Java'],
    [4, 'C#'],
    [5, 'C']
]);

console.log(topProgrammingLanguages);
//end of using an array.

Output

Image 3

Using the set() Method

JavaScript
//using the set method
let myFavoriteBooks = new Map();
myFavoriteBooks.set(1, 'Rich Dad Poor Dad');
myFavoriteBooks.set(2, 'The Magic of Thinking Big');
myFavoriteBooks.set(3, 'Think and Grow Rich');
myFavoriteBooks.set(4, 'How to Win Friends & Influence People');
myFavoriteBooks.set(5, 'Shoe Dog');

console.log(myFavoriteBooks);
//end of using set method

Output

Image 4

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.

JavaScript
let sqlServerInstances = new Map();

sqlServerInstances.set('SQL_DEV_Instance', 'MS_SQLSERVER_1');
sqlServerInstances.set('SQL_UAT_Instance', 'MS_SQLSERVER_2');
sqlServerInstances.set('SQL_PROD_Instance', 'MS_SQLSERVER_3');

console.log(sqlServerInstances.get("SQL_DEV_Instance"));   //output: MS_SQLSERVER_1 
console.log(sqlServerInstances.get('SQL_UAT_Instance'));   //output: MS_SQLSERVER_2 
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.

JavaScript
let sqlServerInstances = new Map();

sqlServerInstances.set('SQL_DEV_Instance', 'MS_SQLSERVER_1');
sqlServerInstances.set('SQL_UAT_Instance', 'MS_SQLSERVER_2');
sqlServerInstances.set('SQL_PROD_Instance', 'MS_SQLSERVER_3');

console.log(sqlServerInstances.has("SQL_PROD_Instance"))   //output: true
console.log(sqlServerInstances.has("SQL_PROD2_Instance"))  //output: false

Using the clear() Method

This method clears the entire Map collection.

JavaScript
let products = new Map();

products.set("PRODUCT_001", { name: "Product 1" });
products.set("PRODUCT_002", { name: "Product 2" });
products.set("PRODUCT_003", { name: "Product 3" });

//let's get the size of the Map before invoking clear()
console.log(products.size);  //output: 3
products.clear();            //clears the Map-products
console.log(products.size);  //output: 0

Using the delete() Method

This method removes the key-value pair inside the Map.

JavaScript
let sqlServerInstances = new Map();

sqlServerInstances.set('SQL_DEV_Instance', 'MS_SQLSERVER_1');
sqlServerInstances.set('SQL_UAT_Instance', 'MS_SQLSERVER_2');
sqlServerInstances.set('SQL_PROD_Instance', 'MS_SQLSERVER_3');

//let's delete the UAT instance
console.log(sqlServerInstances.get('SQL_UAT_Instance'));    //output: MS_SQLSERVER_2 
console.log(sqlServerInstances.delete('SQL_UAT_Instance')); //deletes the key/value pair
console.log(sqlServerInstances.has('SQL_UAT_Instance'));    //output: false
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 started 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.

JavaScript
let myFavoriteBooks = new Map();
myFavoriteBooks.set(1, 'Rich Dad Poor Dad');
myFavoriteBooks.set(2, 'The Magic of Thinking Big');
myFavoriteBooks.set(3, 'Think and Grow Rich');
myFavoriteBooks.set(4, 'How to Win Friends & Influence People');
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.

JavaScript
const myMap1 = new Map([[1, 'red'], [2, 'blue']]);
console.log(myMap1.keys());     //output: { 1, 2 }

Iterate Over keys

JavaScript
//iterate over the keys 
/**
 * Output
 * 1
 * 2
 * 3
 * 4
 * 5
 */
for (const key of myFavoriteBooks.keys()) {
    console.log(key);
}
//end of iteration over the keys 

Using the values() Method

This method return the values for each element in the Map object. Moreover, like the keys method which is an exact opposite of this method, that is solely focus on getting the values of the Map collection.

JavaScript
const myMap2 = new Map([['Electronic Gadget', 'Smart Phone'], ['Input Devices', 'Mouse']]);
console.log(myMap2.values());   //output: {"Smart Phone", "Mouse"}

Iterate Over values

JavaScript
//iterate over the values
/**
 * Output
 * Rich Dad Poor Dad
 * The Magic of Thinking Big
 * Think and Grow Rich
 * How to Win Friends & Influence People
 * Shoe Dog
 */
for (const value of myFavoriteBooks.values()) {
    console.log(value);
}
//end of iteration over the values

Using the entries() Method

This method return the object that contains the [key,value] pairs for each element in the Map collection.

JavaScript
const myMap3 = new Map([['Samsung', 'Smart Phone'], 
               ['Colgate', 'Toothpaste'], ['Coke', 'Soda']]);
console.log(myMap3.entries());   //output: {"Samsung" => "Smart Phone", 
                                 //"Colgate" => "Toothpaste", "Coke" => "Soda"}

Iterate Over entries

JavaScript
//iterate over the entries
/**
 * Output
 * 1 "Rich Dad Poor Dad"
 * 2 "The Magic of Thinking Big"
 * 3 "Think and Grow Rich"
 * 4 "How to Win Friends & Influence People"
 * 5 "Shoe Dog"
 */
for (const [key, value] of myFavoriteBooks.entries()) {
    console.log(key, value);
}
//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:

JavaScript
let fastFoods = new Map([[1, 'McDO'], [2, 'Burger King'], [3, 'KFC'], 
                        [4, 'Wendys'], [5, 'Pizza Hut']]);

console.log(...fastFoods.keys());
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 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 this article, as I have enjoyed writing it. Stay tuned for more. Don’t forget to subscribe, if you haven’t subscribed yet. Many thanks, until next time, happy programming!

History

  • 1st September, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)