Introduction to Map Object in JavaScript

Chao-Wei Peng
Sep 26, 2019 · 2 min read

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:

2. Put key-value pairs into Map object:

3. Access value by 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:

2. Using for … of loop:

3. Using forEach method:

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:

IT Stuff

All sorts of developer topics in IT.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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