How Maps work in JavaScript

Map is one of the data structures that comes with the ECMAScript 6.

Isha Jauhari
Feb 11 · 3 min read

Map is list of items where each item is stored as a key,value pair. Sounds familiar to Object? Then what is difference between Object and Map?

  • Unlike object, map is used to store the key and value of any type. It can be number, String, Boolean… Map can use both Objects and primitive types as keys.
  • Maps are iterable by-default, whereas Objects are not.
  • The key,value pairs in Map maintains the insertion order, whereas Object don’t.

Initializing Map

We can create the instance of map using the new Map(). We can initialize a map with array of arrays, where each array represents the key,value pair.

The first item in the array becomes the key and second will be value.

Methods

  • map.set(key, value) : sets the value for the specified key in the map object.
  • map.get(key) : returns the value by key.If key is not present in map object,it returns undefined.
  • map.has(key) : returns true if key is present in the map object otherwise false.
  • map.delete(key) : returns true if the element is removed in the map object otherwise false.
  • map.clear(key) : removes the entire key,value pairs exists in the map object.

Properties

  • map.size : returns the total number of key,value pair exists in the map object.

Few Examples

Iterating Map Object

For..of loop

We can iterate over map using for..of loop. Below are the methods used for iteration over for…of loop:

  • map.keys(): This method is used to retrieve the keys present in the map object.
  • map.values(): This method is used to retrieve the values present in the map object.
  • map.entries(): This method is used to retrieve the key, value pair present in the map object. By default for..of loop gives the key, value pair.

foreach loop

We can iterate over map using foreach loop.

That’s it for now, hope it was useful. In next article, I will cover Set Data Structure.

JavaScript in Plain English

Learn the web's most important programming language.

Isha Jauhari

Written by

Trying to learn new things every day and sharing my knowledge with people || Avid Reader

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade