IT Stuff
Published in

IT Stuff

Introduction to Map Object in JavaScript

In software development, there is an important data structure help us manage key-value pairs, where we can access value by key directly.

In JavaScript, we are used to apply plain object for storing key-value pairs. But now, in ES 6 version, we are introduced a new built-in data structure, called Map, providing better support for accessing key-value data.

Photo by Aaron Burden on Unsplash

How to Use Map Object?

Basically, we take 3 steps to use Map object:

1. Build a Map object:

let map=new Map();

2. Put key-value pairs into Map object:

map.set("a", "apple"); // map.set(key, value);
map.set("b", "banana");

3. Access value by key:

let data;
data=map.get("a"); // return "apple"
data=map.get("c"); // return undefined if there is no matched key

Size and Iterating

We can keep track of how many entries of key-value pairs in a Map object or iterate over it with few lines.

1. Get size of Map object:

// we use map variable, comes from above example
console.log(map.size); // print current size of map object

2. Using for … of loop:

for(let entry of map){ // iterating over map object
console.log("Key:", entry[0], "Value:", entry[1]);
}
// print out following results
// Key: a Value: apple
// Key: b Value: banana

3. Using forEach method:

map.forEach((value, key)=>{
console.log("Key:", key, "Value:", value);
});
// print out following results
// Key: a Value: apple
// Key: b Value: banana

Should we use Map Object?

Map object, as a key-value store solution, has some advantages over simple plain object:

  1. Keys in Map object can be a string or any other object, even if null and undefined are acceptable keys.
  2. Map object keeps order of data inside. While iterating over it, a Map object returns data in order of insertion.
  3. We can track size of a Map object easily by accessing size member.
  4. We can iterate a Map object efficiently by for … of loop.

But there are still few shortages listed below:

  1. It’s a bit slower than plain object while adding key-value pairs.
  2. We should write a little more code to do the same simple task, if we use Map object than plain object.

Browser Support

Even if Map object is relative new feature in JavaScript, browser support for it is pretty good. For now, only IE (exclude Edge) don’t support Map object. (who cares)

More Stories:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chao-Wei Peng

Chao-Wei Peng

Founder and Web Instructor. Welcome to My Website: https://training.pada-x.com/