Maps in Javascript

Introduction

If you are a web developer guy, you must have come across data structures like List and Object in Javascript. While those are really great, they are probably not enough when it comes to solving certain kinds of problems.

In this blog, we will go through Maps in Javascript and try to understand what it is, what are the different methods exists for maps, how to iterate over it and how it is different from a traditional Object in Javascript.

So, what are Maps?

Maps, like Objects, store key-value pairs. Yup, that's it. What's the difference then? The difference is in the type of keys that Objects and Maps use. Also, the order in which key-value pairs are stored in maps is preserved.

While Objects simply allow for keys that are Strings, with maps, the keys can be of any type. Yup, you heard it right. It can be Numbers, Float, Boolean, String, Object, NaN, Array, etc.

While we now understand the basic difference between Objects and Maps, let us now look at some of the methods that will allow us to create maps, and perform some operations on them.

Methods in Maps

  • new Map(iterable) - This method takes an iterable as an input (an array of key-value pairs), and creates a map out of it.
let map = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

//Loggin the newly created map in the console would show the following: Map(3) {"a" => 1, "b" => 2, "c" => 3}
  • map.set(key, value) - This method is used to insert a new key-value pair into a map.
let map = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

map.set('d', 4);
  • map.has(key) - .has() method is used to check for the existence of a key in the map. It returns a boolean - true if it exists, false if it doesn't.
let map = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

map.set('d', 4);

console.log(map.has('a')); //Would return true as it does exist in the map that we have created.
  • map.get(key) - .get() method is used to access a value associated with a key in a map.
let map = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

console.log(map.get('a')); // This would return 1 as it is the associated value with the key 'a'.

Here's the thing: map[key] would do the same thing as map.get(key), but it is still not the right way to use maps. Trying to access the value using map[key] is the same as trying to access a value to a key in Objects; it treats the map as an object (keys are of type Strings).

  • map.delete(key) - This method would delete the value associated with a key, along with the key itself.
let map = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

map.delete('c');

console.log(map); // Map(2) {"a" => 1, "b" => 2}
  • map.clear() - .clear() method results in the deletes all the key-value pairs in a map.
let map = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

map.clear();

console.log(map); // {}
  • map.size - This returns the size of the map.
let map = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

console.log(map.size); // output - 3

Iterables in Maps

  • map.keys() - Returns an iterable for keys in maps.
let map = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

for(let key of map.keys()) {
  console.log(key);
}

/* OUTPUT:
    a
    b
    c 
*/
  • map.values() - Returns an iterable for values in maps.
let map = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

for(let value of map.values()) {
  console.log(value);
}

/* OUTPUT:
    1
    2
    3 
*/
  • map.entries() - Returns an iterable for key-value pairs in maps.
let map = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

for(let entry of map.entries()) {
  console.log(value);
}

/* OUTPUT:
    ['a', 1]
    ['b', 2]
    ['c', 3]
*/
  • forEach - The map has a built-in forEach method that can be used to iterate over the contents of the map.
let newMap = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

newMap.forEach((value, key, map) => {
  console.log(`${value} , ${key}`);
});

/* OUTPUT:
    1 , 'a'
    2 , 'b'
    3 , 'c'
*/

Creating Objects out of Maps and vice-versa

With Object.entries() and Object.fromEntries(), we can create an object out of a map and a map out of an object.

  • Object.entries() - This takes an object as an input and returns an array of key-value pairs, that is used in the creation of a map.
let obj = {
  'a': 1,
  'b': 2
};

let newMap = new Map(Object.entries(obj));

console.log(newMap);

/* OUTPUT:
Map(2) { 'a' => 1, 'b' => 2 }
*/
  • Object.fromEntries() - This takes a map as an input and creates an object out of the key-value pairs stored in the map.
let newMap = new Map([ 
      ['a', 1], ['b', 2], ['c', 3]
]);

let obj = Object.fromEntries(newMap);
console.log(obj);

/* OUTPUT: 
{ a: 1, b: 2, c: 3 }
*/

Links

Below is the link, where you can find the source code related to the implementation of the above-mentioned methods, and iterables in maps, in Github. Do check it out for your reference.

Implementation of all the discussed concepts of maps in Javascript

Final Thoughts

That's it, folks. I am new to writing technical blogs, and I decided to do it as I think it is the best way to revise anything that I am learning currently. Also, sharing knowledge with others is cool. Over the next few days, I will be writing more on other data structures in Javascript like Set, Weakmap, and Weakset. Stay tuned for more.

You can follow me on GitHub, and LinkedIn.