JavaScript Map Data Structure

JavaScript Map Data Structure with Examples

In this article, I am going to discuss the JavaScript Map Data Structure with Examples. JavaScript ECMAScript6 (ES6) introduces four new data structures: Set, WeakSet, Map, and WeakMap. We already learned Set, WeakSet. We will discuss the WeakMap Data Structure in our next article. Let’s start exploring and understanding the following pointers in detail about the JavaScript Map object.

  1. Why JavaScript Map Data Structure?
  2. What is Map in JavaScript?
  3. Where to use Map Data Structure in JavaScript?
  4. JavaScript Map Object Methods
  5. Creating a Map Object in JavaScript
  6. Adding/Setting an element to a Map in JavaScript
  7. Getting an element of a Map Object in JavaScript
  8. Removing an element from a Map Object in JavaScript
  9. Checking if an element key exists in a Map
  10. Clearing a Map in JavaScript
  11. Getting Map Length in JavaScript
  12. Convert map keys or values to an array in JavaScript
  13. Iterating Maps in JavaScript
  14. Understanding entries(), keys(), and values() method of Map
  15. Object Vs Map in JavaScript
  16. When to use Map and when to use Object?
Why JavaScript Map Data Structure?

Prior to ES6, when we need to map keys to values, we mostly use an object, because an object allows us to map a key to a value of any type. The JavaScript plain object have this format: { key: ‘value’ } to holds structured data. But the plain object has a limitation: its keys have to be strings (or Symbols). If we use numbers as a key. And when accessing the object keys, it returns the numbers which got converted to strings by the plain object.

Example: JavaScript plain object example
<html>
<head>
    <title>JavaScript plain object example</title>
</head>
<body>
    <script>
        const cities = {
            1: 'Mumbai',
            2: 'Pune',
        };

        Object.keys(cities); // => ['1', '2']
        console.log("JavaScript Plain Object Keys:", Object.keys(cities));
    </script>
</body>
</html>

Output:

avaScript plain object example

Issues with plain Object are key to string conversion, it’s impossible to use an object’s as key, etc this all got resolved by Map object. Plain JavaScript holds the structured data in key-value format. But they have some limitations.

However, using an object as a map has some side issues:

  • An object always has a default key like the prototype has. Objects are for storing keyed collections.
  • A key of an object must be a string or a symbol, we cannot use an object as a key.
  • An object does not have a property that shows the size of the map.

These limitations are solved by Map. ES6 provides a new collection type called Map that overcomes these issues.

What is Map in JavaScript?

A Map, as the name implies, is a basic mapping of keys to values. A Map is a key-value data structure in ES6. A Map object stores each element as Key-value pairs in the format – (key, value), which contains a unique key and value mapped to that key. And due to the uniqueness of each stored key, there is no duplicate pair stored.

JavaScript Maps are an object that allows us to store collections in key-value pairs. We can think of how a dictionary works in the sense that if we want to know the definition of a particular word (the value), we only need to search the word itself (the key). Maps are different from objects because their keys can be anything (primitive values as well as objects), not just strings and symbols.

One of the important differences between Maps and Objects is that Map allows us to use anything for the keys. We are not restricted to primitive values like symbols, numbers, or strings, but also, we can even use functions, objects, and dates – too. Keys won’t be converted to strings as regular plain JavaScript objects do.

Iteration over Maps is always done in the order the items were inserted into the Map (Insertion Order), whereas when iterating over keys in an object, the order is undefined.

Where to use Map Data Structure in JavaScript?

Map stored data in key-value pairs in the format – (key, value). Hence Map is used for fast searching and looking up data.

Features of Map
  • Map – is a collection of keyed-values.
  • A Map object contains unique keys. It cannot contain duplicate keys.
  • A Map object can contain duplicate values.
  • In Map Object, the key and value can be of any type (primitive values as well as objects).
  • The Map accepts keys of any type: strings, numbers, Boolean, symbols.
  • A Map object iterates its elements in insertion order.
  • The map can also use objects as keys.
Syntax to use Map Data Structure in JavaScript:

The below syntax creates a new Map
new Map([iterable])

The Map constructor also accepts an optional iterable object whose elements are key-value pairs.
iterable: It can be any iterable object (for example an array) containing elements in the form of [ key, value] pairs.
key: The key of an element
value: The value assigned to that key.

JavaScript Map Object Methods

The Map object provides the following useful methods:

JavaScript Map Object Methods

Creating a Map in JavaScript

Creating a Map in JavaScript is the same as creating any object; by using the new keyword. To create a Map, use the Map constructor.
let myMap = new Map();

we can also provide Map object with any object that has iterable features and produces a collection such as [ [‘key’, ‘value’], [‘key’, ‘value’] ]. The Map constructor accepts any iterable object as an optional parameter such as an array which contains an array of two elements: the first element is the key, and the second element is the value. Let see this below example:

Example: JavaScript Map example
<html>
<head>
    <title>JavaScript Map example</title>
</head>
<body>
    <script>
        let myMap = new Map([
            [new Date(), function todayDate() { }],
            [() => 'key', { prop: 'value' }],
            [Symbol('items'), [1, 2]],
            [document.body, "document body"]
        ]);

        console.log("Map example:", myMap);
        console.log("type of myMap:", typeof(myMap));
        let result = myMap instanceof Map;
        console.log("check if mySet instance of Set:", result);
    </script>
</body>
</html>

Output:

JavaScript Map example

All elements in the Map are of any type with the key-value format as we saw in the above example. When we use the typeof operator to the myMap, it returns an object. The myMap is an instance of Map type hence the above result statement returns true.

Adding/Setting an element to a Map in JavaScript

Once we have created our Map, adding an element to a Map is done by setting an element. The idea here is that we are ‘setting’ an entry into our Map by assigning a value to a key. To add an element to a Map, use the set() method and pass the key and value:
myMap.set(key,value);
myMap.set(‘prop1’, 123);

As we know that it contains a unique key and value mapped to that key. And due to the uniqueness of each stored key, there is no duplicate pair stored. If the key already exists in the map it will not be added again, as Map contains unique keys and value mapped to that key. Note that the set() method returns the map itself, so we can chain set() calls together, Hence the set() method is chainable.
myMap.set(‘prop1’, 123).set(‘prop2’, 456).set(‘prop3’, 432);

Setting a key over and over again meaning setting a duplicate key will overwrite its value with a new one.

Example: JavaScript Map set() method example
<html>
<head>
    <title>JavaScript Map set() method example</title>
</head>
<body>
    <script>
        let myMap = new Map();
        myMap.set('prop1', 123);
        myMap.set('prop1', 456);
        myMap.set('prop2', 'abc');
        myMap.set('prop2', 'def');
        myMap.set('prop3', 'Hello Map');
        myMap.set(new Date(), function todayDate() { });
        myMap.set(() => 'key', { pony: 'value' })
             .set(Symbol('items'), [1, 2]); //set() method is chainable
        console.log("Map set() method example:", myMap);
    </script>
</body>
</html>

Output:

Adding/Setting an element to a Map in JavaScript

In the above example we have seen Map allow only unique Keys and setting a duplicate key again and again will overwrite its value such as 123 got overwrite with 456 of prop1 and abc got overwrite with def of prop2.

Getting an element of a Map Object in JavaScript

After we have populated a map with some elements, we can get them back by using the get() method and passing in the element key. To get the value associate with the key, use the get() method.

myMap.get(key)

This function will return element value mapped with the specified key if the element existed in the map, or otherwise undefined. The below example elaborates it properly.

Example: JavaScript Map get() method example
<html>
<head>
    <title>JavaScript Map get() method example</title>
</head>
<body>
    <script>
        let myMap = new Map();
        myMap.set('prop1', 123);
        myMap.set('prop1', 456);
        myMap.set('prop2', 'abc');
        myMap.set('prop2', 'def');
        myMap.set('prop3', 'Hello Map');

        let item1 = myMap.get('prop3');
        let item2 = myMap.get('prop1');
        let item3 = myMap.get('prop5');
        console.log("Map get() method example -item1:", item1);//element present in the map
        console.log("Map get() method example -item2:", item2);
        console.log("Map get() method example -item2:", item3);//element not present in the map       
    </script>
</body>
</html>

Output:

Getting an element of a Map Object in JavaScript

Also to get the element of the iterable objects such as array for that we need to call the keys(), values(), and entries() method that will see in coming examples.

Removing an element from a Map Object in JavaScript

To get rid of an element in a Map after it has been set, call the delete() method on it and pass in the element key we want to remove. To remove an element from a map use the delete() method and pass the element key.

myMap.delete(key); This function will return true if the element existed in the map and was successfully removed, or otherwise false.

Example: JavaScript Map delete() method example1
<html>
<head>
    <title>JavaScript Map delete() method example1</title>
</head>
<body>
    <script>
        let myMap = new Map();
        myMap.set('prop1', 123);
        myMap.set('prop2', 'abc');
        myMap.set('red', 'rose')      
      	     .set('blue', 'blueberry')
             .set('brown', 'chocolate');//set() method is chainable

        console.log("Map after Adding value:", myMap);
        console.log("Getting Map element by passing key:", myMap.get('prop2'));
        
 myMap.delete('prop2');
        console.log("Map after Deleting element:", myMap);
        console.log("Getting Map element by passing key:", myMap.get('prop2'));//undefined as its deleted from Map
    </script>
</body>
</html>

Output:

JavaScript Map delete() method example

Example: JavaScript Map delete() method with iterable object(array) example
<html>
<head>
    <title>JavaScript Map delete() method with iterable object(array) example2</title>
</head>
<body>
    <script>
        let myMap = new Map([[10, 20], [300, 500], [34, 45]]);

        console.log("Map after Adding value:", myMap);
        console.log("Getting Map element by passing key:", myMap.get(10));
       
  myMap.delete(10);
        console.log("Map after Deleting element:", myMap);
        console.log("Getting Map element by passing key:", myMap.get(10));//undefined as its deleted from Map
    </script>
</body>
</html>

Output:

JavaScript Map delete() method with iterable object(array) example

Checking if an element key exists in a Map

Instead of getting an element and then checking if it is null or even if it exists at all, we can use the has() method and pass the element key to check if a map has a key and it returns true if it exists and false if it’s not. To check if a key exists in a map, use the has() method and pass the element key.

myMap.has(key)

Example: JavaScript Map has() method example
<html>
<head>
    <title>JavaScript Map has() method example</title>
</head>
<body>
    <script>
        let myMap = new Map();
        myMap.set('prop1', 123);
        myMap.set('prop2', 'abc');
        myMap.set('red', 'rose')
             .set('blue', 'blueberry')
             .set('brown', 'chocolate');

        console.log("Check if myMap contains red:", myMap.has('red'));//true
        console.log("Check if myMap contains yellow:", myMap.has('yellow'));//false

        let valueMap = new Map([[20, 40], [60, 70], [33, 55]]);
        console.log("Check if valueMap contains 60:", valueMap.has(60));
        console.log("Check if valueMap contains 100:", valueMap.has(100));
    </script>
</body>
</html>

Output:

Checking if an element key exists in a Map

Clearing a Map in JavaScript

Clearing a Map will delete all elements inside it, it will reset it to a state as if it were a brand-new map. To remove all elements from a Map, use the clear() method

myMap.clear()

Example: JavaScript Map clear() method example
<html>
<head>
    <title>JavaScript Map clear() method example</title>
</head>
<body>
    <script>
        let myMap = new Map();
        myMap.set('prop1', 123);
        myMap.set('prop2', 'abc');
        myMap.set('red', 'rose')
             .set('blue', 'blueberry')
             .set('brown', 'chocolate');

        console.log("myMap after adding the elements:", myMap);

        myMap.clear()
        console.log("myMap after clearing all the elements:", myMap); //{}        

        let valueMap = new Map([[20, 40], [60, 70], [33, 55]]);
        console.log("valueMap after adding the elements:", valueMap);

        valueMap.clear()
        console.log("valueMap after clearing all the elements:", valueMap); //{}        

    </script>
</body>
</html>

Output:

JavaScript Map clear() method example

Getting Map Length in JavaScript

Getting the size of a map is as simple as just using the size property. To get the numbers of elements present in Map, use size property. myMap.size; This property, unlike Array.prototype.length, is read-only, which means that we can’t change its value by assigning some other value to it.

Example1: JavaScript Map size example
<html>
<head>
    <title>JavaScript Map size example1</title>
</head>
<body>
    <script>
        let myMap = new Map();
        myMap.set('prop1', 123);
        myMap.set('prop2', 'abc');
        myMap.set('red', 'rose')
             .set('blue', 'blueberry')
             .set('brown', 'chocolate');

        console.log("Size of myMap is:", myMap.size);

        let valueMap = new Map([[20, 40], [60, 70], [33, 55]]);
        valueMap.size = 10 //size property is read-only. Hence can’t change it by assigning something to it.
        console.log("Size of valueMap is:", valueMap.size);      
    </script>
</body>
</html>

Output:

Getting Map Length in JavaScript

In Strict mode, when we try to change the size property of Map it even throws an error: TypeError: Cannot set property size of #<Set> which has only a getter

Example2: Map size with strict mode
<html>
<head>
    <title>JavaScript Map size with strict mode example2</title>
</head>
<body>
    <script>
        "use strict"

        let myMap = new Map();
        myMap.set('prop1', 123);
        myMap.set('prop2', 'abc');
        myMap.set('red', 'rose')
             .set('blue', 'blueberry')
             .set('brown', 'chocolate');

        console.log("Size of myMap is:", myMap.size);

        let valueMap = new Map([[20, 40], [60, 70], [33, 55]]);
        valueMap.size = 10 //size property is read-only. Hence can’t change it by assigning something to it.
        console.log("Size of valueMap is:", valueMap.size);      
    </script>
</body>
</html>

Output:

Map size with strict mode

Convert map keys or values to an array in JavaScript

Sometimes we may need to convert a Map to an array when we want to work with an array instead of an iterable object. In order to do so, we can use Array.from(). We can create an Array from a Map using Array.from or the spread operator. About Spread operator we will learn more in detail in their respective chapters.

The below example depicts the relation with the array object and how the 2-D array i.e.: [[ key1, value1], [key2, value2]] converted to map and then converted back to the 2-D array using Array.from or the spread operator.

Example: JavaScript Converting array to Map and then converting Map to an array
<html>
<head>
    <title>JavaScript Converting array to Map and then converting Map to array using Array.from and Spread operator example</title>
</head>
<body>
    <script>
        let twoDArray = [['mum', 'Mumbai'], ['ind', 'India']]

        let myMap = new Map(twoDArray);

        myMap.get('mum');//Mumbai
        console.log('myMap key:mum value is:', myMap.get('mum'));

        // Use Array.from() to transform a map into a 2D key-value Array
        console.log('myMap to 2Darray using Array.from()', Array.from(myMap)) // Will show you exactly the same Array as kvArray

        // A short way to do the same, using the spread syntax
        console.log('myMap to 2Darray using spread operator', [...myMap]);

        // Or use the keys() or values() iterators, and convert them to an array
        console.log('use the keys() iterator and convert them to an array', Array.from(myMap.keys())) // ["mum", "ind"]

    </script>
</body>
</html>

Output:

JavaScript Converting array to Map and then converting Map to an array

Iterating Maps in JavaScript

JavaScript Map has 3 functions/methods which returns the iterators:

  • keys()
  • values()
  • entries()

from the above three methods, entries() is the default method for Map iterators and it contains [key, value] pairs of each element in the Map object in insertion order. it’s used by default in for..of loop. We can use a simple for-of loop to iterate a Map. When iterating over a Map, it will always return keys and values in the insertion order, meaning in the order they were first added to the Map.

Example: JavaScript Map default iterator example
<html>
<head>
    <title>JavaScript Map default iterator example</title>
</head>
<body>
    <script>
        let myMap = new Map();
        myMap.set('one', 10);
        myMap.set('two', 20);
        myMap.set('three', 30);

        console.log("myMap elements is:", myMap);
        for (let [key, value] of myMap) {
            console.log(`myMap Key: ${key} and Value: ${value}`);
        }

        for (let [key, value] of myMap.entries()) {
            console.log(`myMap with entries() Key: ${key} and Value: ${value}`); //will give same output
        }
    </script>
</body>
</html>

Output:

JavaScript Map default iterator example

So from the above example, it’s clear that the map default iterator is entries() method only. even if we don’t specify the method it will give us a similar output when using the entries() method. There’s also a forEach() method, same as Array.prototype.forEach(). If we want to invoke a callback function on each element of a Map, we can use the forEach() method.

forEach(callback [, thisArg])

It has two parameters, first is the callback, which will be executed once for each element present in the Map object, and the Second parameter is optional thisArg. If thisArg parameter is provided then it will be used as this value for each call of the callback function. The Callback function has three parameters. value, key, and the map object. The first two parameters are values and keys of the map object and the third argument is the Map itself.

myMap.forEach((value, key, mapObject) => console.log(key,value));

Example: JavaScript Map iterating with for-of and for each loop example
<html>
<head>
    <title>JavaScript Map iterating with for-of and foreach loop example</title>
</head>
<body>
    <script>
        let myMap = new Map();
        myMap.set('one', 10);
        myMap.set('two', 20);
        myMap.set('three', 30);

        console.log("myMap elements is:", myMap);

        //Iterate myMap entries with for-of loop
        for (let [key, value] of myMap) {
            console.log(`Iterate myMap entries with for-of loop. Key: ${key} and Value: ${value}`);
        }

        //Iterate myMap entries with forEach()
        myMap.forEach((value, key, myMap) => console.log(`Iterate myMap entries with forEach(). Key: ${key} and Value: ${value}`)); 
            
    </script>
</body>
</html>

Output:

JavaScript Map iterating with for-of and for each loop example

entries(), keys(), and values() method of Map

The entries() method is the default method of Map iterator and it contains [key, value] pairs of each element present in the map.

keys() method iterate overs the map keys. To get the key of a map object, we use the keys() method. This method returns the new iterator object that contains the keys of the elements present in the map.

values() method iterate over the map values. To get the value of a map object, we use the values() method. This method returns the new iterator object that contains the values of the elements present in the map.

myMap.entries();

myMap.keys();

myMap.values();

Example: JavaScript Map iterating entries(), keys() and values() example
<html>
<head>
    <title>JavaScript Map iterating entries(), keys() and values()example</title>
</head>
<body>
    <script>
        let myMap = new Map();
        myMap.set('one', 10);
        myMap.set('two', 20);
        myMap.set('three', 30);
        myMap.set('four', 40);
        myMap.set('five', 50);

        console.log("myMap elements is:", myMap);

        //Iterate myMap entries with for-of loop,entries()
        for (let [key, value] of myMap.entries()) {
            console.log(`Iterate myMap with entries(). Key: ${key} and Value: ${value}`);
        }

        //Iterate myMap with keys()
        for (let key of myMap.keys()) {
            console.log(`Iterate myMap with keys(). Key: ${key}`);
        }

        //Iterate myMap with values()
        for (let value of myMap.values()) {
            console.log(`Iterate myMap with values(). Value: ${value}`);
        }
    </script>
</body>
</html>

Output:

JavaScript Map iterating entries(), keys() and values() example

Object Vs Map in JavaScript
  1. The object can have a number, string, and symbol as a key whereas in Map we can put any type of data as a key.
  2. The object is not ordered and not iterable whereas Map is ordered and iterable.
  3. In an object, we have to manually keep track of the size of an Object while we can get the size of a Map easily.
  4. The iteration of an object is in arbitrary order while the iteration of Map is in insertion order.
  5. An object has a prototype, so it contains a default key whereas Map does not contain any default keys.
  6. The object is not an instance of a Map while Map is an instance of an Object.
When to use Map and when to use Object?
  1. The object is a great choice when we only need a simple structure to store the data and also knew that all the keys are either string, integer, or symbol.
  2. Use Map when keys are unknown till run time and when all the keys and all the values are the same types.
  3. Use Map when in case there is a requirement to stored primitive values (number, Boolean, string, symbol, etc) as keys because as we know that object treats each key as a string.
  4. Map performs better and faster than Object in storing large sets of data when the keys are unknown till run time.

In the next article, I am going to discuss JavaScript WeakMap Data Structure with Examples. Here, in this article, I try to explain the JavaScript Map Data Structure with examples. I hope this JavaScript Map Data Structure article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this JavaScript Map Data Structure article.

Registration Open For New Online Training

Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.

Leave a Reply

Your email address will not be published. Required fields are marked *