Simple guide to Javascript Map data structure

0
535
Simple guide to Javascript Map data structure

From ECMAScript 2015, Javascript Map was created to represent exact map data structure so Javascript developers don’t have to worry about side-effects when dealing with map using regular Javascript objects.

In this article, I will walk you through everything of Javascript Map.

Javascript Map

Let’s take a look at Javascript Map to see how it works.

Description

Map by definition is basically a collection that holds data in key-value pair.

This is what map is described at official MDN documentation:

The Map object holds key-value pairs. Any value (both objects and primitive values) may be used as either a key or a value.

Nothing new at all, but there is one point that makes Map differs from Javascript object:

  • Key and value in Map can be both primitive values (string, number, …) and objects.

Do you see the interesting point?

Anything can be key or value in a Map object. Even NaN can be either key or value, too.

Usage

Map is provided with following constructors, properties and methods.

Constructor

You can initialize an empty Map

let map = new Map();

Since Map is still an object, we have to use new keyword to create a new object. That’s pretty clear!

You can also create a new Map with a preset of data. The initial data should be an iterable key-value pair array.

So it will look like this.

const INITIAL_DATA = [
    ['greet', 'how are you Javascript developer?'],
    [2, 2018],
    [{}, { 'title': 'Simple guide to Javascript Map data structure' }]
];

let map = new Map( INITIAL_DATA );
Properties

At the time of this writing, Map has only single property.

  • size : returns number of key-value pairs in Map.
Methods

The four basic methods of Map are supported, including:

  • set(key, value) : add a new key-value pair.
  • get(key) : get value of a given key.
  • delete(key): delete a key-value pair by key.
  • clear(): empty a Map object.

Those methods’s usage is pretty straightforward.

let map = new Map();

map.set('website', 'KodeMate');
map.set({}, 2018);
map.set(NaN, 42);

console.log(map.get('website')); // returns "KodeMate"
console.log(map.get({})); // returns "2018"
console.log(map.get(NaN)); // returns "42"

map.delete({}); // only two pairs left ("website", "KodeMate") and (NaN, 42)

map.clear(); // empty map now

Another three methods to query collection of keys and values in the map:

  • keys(): returns an Iterator object that contains all keys in Map according to the insertion order.
  • values(): return an Iterator object that contains all values in Map according to the insertion order.
  • entries() : return an Iterator object that contains an array of [key, value] pair sorted by insertion order.

When iterating through a Javascript object, keys and values are returned in random order. But with Map, everything is returned in insertion order.

let map = new Map(...);

for (var key of map.keys()) {
    console.log('Key: ' + key);
}

for (var value of map.values()) {
    console.log('Value: ' + value);
}

for (var [key, value] of map.entries()) {
    console.log('Key: ' + key + '| Value: ' + value);
}

This saves a lot of time compared to working with Javascript object as map.

To iterate through Javascript Map, you can use forEach(callback(value, key)). The callback provides two arguments sequentially standing for value and key of the iteration entry. For example,

let map = new Map();

map.set('website', 'KodeMate');
map.set({}, 2018);
map.set(NaN, 42);

map.forEach(function(value, key) {
    console.log('Key: ' + key + ' | Value: ' + value);
});

Comparing Map and Javascript object

Even though Javascript object can work as a Map; still, it doesn’t reflect a true map data structure.

Here are some notable points you need to consider:

  • Javascript object can hold only string as keys while Map can hold both objects and any primitive types as keys or values.
  • Javascript object contains several default keys like Object.prototype . This is often bypassed with Object.create(null). You don’t have to do anything for Map.
  • Map.size returns the correct number of entries automatically. But for Javascript object, you have to manually keep track of each map entry.
  • Map stores data by insertion order while Javascript retuns in random order.
  • Map provides utility methods like clear() forEach() and can be iterated through all entries easily. This is complicated for Javascript object.

Up to this point, do you think it is good to use Map now instead of good old Javascript object?

I, personally, think it’s a good time to pick it up and use Map to its true purpose. You should, too!

Some tips using Map

As a bonus, I would like to share some tips when using Map in Javascript ES6.

Use Object.entries() to initialize data for `Map`

Yes, Object.entries() returns an iterable key-value pair array, so you can use it.

let map = new Map(Object.entries({
    'title': 'Simple guide to Javascript Map data structure',
    'year' : 2018
}));
Use for..of to Map object directly

As mentioned above, you can loop through all entries in Map object using entries().

However, you can just use for..of to iterate through all Map entries directly without calling entries().

for (var [key, value] of map) {
    console.log('Key: ' + key + '| Value: ' + value);
}
Conversion between Map and array

As you know, Map can be converted from an iterable key-value pair array, so the transformation between these two is very flexible.

const INITIAL_DATA = [ 
    ['greet', 'how are you Javascript developer?'], 
    [2, 2018], 
    [{}, { 'title': 'Simple guide to Javascript Map data structure' }] 
]; 

let myMap = new Map( INITIAL_DATA );

var myArray = Array.from(myMap);

You can even flat the keys and values array of Map.

let myKeys = Array.from(myMap.keys());

let myValues = Array.from(myMap.values());

To summarize

Javascript Map by the name has been created to fulfill its true purpose, which is to represent a correct map data structure, to resolve all the problems that Javascript objects can’t help.

Map has its own usage, it’s done a pretty good job.

Up to this point, I guess you should start to get familar with Javascript Map from now. Your daily Javascript life will get easier.

and, the last question?

What about Javascript Map performance? Is it better than just using object?

I’m curious about it too, but still cannot find a good answer for it at the moment. But I’m really certain that either good or bad performance will be improved by all best-in-class professional Javascript engineers who are working hard to improve the language day by day.

I personally think that, if using Javascript Map doesn’t cause any problem for the development then just keep using. When problems arise, I will start looking for supports from all the best developers around the globe.

Finally, if you like this tutorial, please subscribe or follow us on FacebookTwitterGoogle+ and Youtube to get updates on latest programming tutorials.