Simplifying Maps in the JavaScript


Maps is a data structure, which stores the key/value pair in an ordered way.  Since the inception of the JavaScript, objects are primarily used for the map.  Consider the below code listing:

var foo = {
    color : 'Red'

console.log(foo['id']); // 1 
console.log(foo.color); // Red


To store two key/value pairs, we have created an object foo and using the keys such as id and color to retrieve the values. It is straightforward, however using an object for the map has two major challenges,

  1. It is unordered, means it does not remember the original insertion order of the keys
  2. The only string can be used as the key

There is a challenge in using only string as the key. Let us consider the code listed below,

var z = {};

var x  = { id : 1};
    y  = { id : 1};

z[x]= 'foo';
z[y] = 'bar';

console.log(z[x]); // bar 
console.log(z[y]); // bar

Surprisingly bar is printed twice because,

  1. Objects can have an only string as the key
  2. Since x and y both are an object JavaScript is converting them to string  value ‘[object, Object]’
  3. For the z object, there is only one key ‘[object, object]’ is set

You can verify that there is only one key is set for the object z as shown below,

console.log(Object.keys(z)); // [ '[object Object]' ]

These are the problems in using an object as a map. You can solve it by using the Map object introduced in ES6.

var z = new Map();

var x  = { id : 1};
    y  = { id : 1};

console.log(z.get(x)); // foo 
console.log(z.get(y)); // bar

Instead of using square brackets, you use set() for write and get() for reading operations in the Map. The other essentials methods with Map objects are

  1. The delete(key) method – to delete a key
  2. The size() method – return the total number of keys
  3. The clear() method – delete all keys from the Map

These methods can be used as shown in the code listing below,

console.log(z.size); // 2
z.delete(x); // returns true
console.log(z.size); // 1
console.log(z.get(y)); // undefined
console.log(z.size); // 0

One important thing is delete method of the Map object is different from the delete operator, which is used to delete the object’s properties.

Reading values from the Map

You can read values from the Map using the values() method. It returns an iterator object that contains values for all the keys. It returns values in the order they were added to the Map.  You can use values() method as shown below,

var z = new Map();

var x  = { id : 1};
    y  = { id : 1};

z.set('range', 30);
let zvalues = z.values();


The values method return an iterator as shown in the below image,


You can convert an iterator to an array using the spread operator or Array.from as shown in the below code listing:

let zvalues = z.values();
let zvaluesarray = [...zvalues];
let zvaluesarray1 = Array.from(z.values());
console.log(zvaluesarray); // ['foo','bar',30]
console.log(zvaluesarray1); // ['foo','bar',30]



Reading keys from the Map

You can read the keys from the map using the keys() method.

let zkeys = z.keys();
let zkeyaarray = [...zkeys];


You get an output as shown in the below image. Like values(,) method, the keys() method also returns an iterable, and you can use the spread operator to convert it to an array.


You can use has() method to check whether a particular key exists or not, it returns true if the key exists otherwise false.

var z = new Map();
var x  = { id : 1};
    y  = { id : 1};

z.set('range', 30);

console.log(z.has(x)); // true 
console.log(z.has(y)); // false 



The has() method returns false for y as it is not part of the map z.

Initializing Map with the Arrays

The Map constructor can optionally take an iterable object or an array as the parameter. You can pass an array as the parameter to the Map constructor as shown below,

const fooarray = [
    ['1', 'One'],
    ['2', 'Two'],
    ['3', 'Three'],

var z = new Map(fooarray);
console.log(z.get('1')); // 1
let zvalues = z.values();
let zvaluesarray = [...zvalues];
console.log(zvaluesarray); // [ 'One', 'Two', 'Three' ]


The Object and the Map

As we saw that objects could be used to work with key/value pair, however, there are substantial differences between using the object and the Map,

  • You can use functions and objects besides other primitive types as the key in the Map, whereas for the Object only string or Symbols can be used.
  • The keys in the Map are ordered, whereas Keys in the Object are unordered.
  • You can use the size method to find the size of the Map, whereas to find several properties in the Object, you have to do manually
  • A Map is iterable, whereas an Object is not, you need to fetch the keys and then iterate over them manually
  • Each Object has a prototype and its default properties, so you need to make sure that map keys name does not collide with the properties name from the prototype.


One more important factor is frequent read and write operations on a Map could be faster than of an Object.


If you use an object as a key in a Map, and all the references of the object are removed, still object is not eligible for the Garbage Collection until its entry is not deleted from the Map itself.  Therefore, if a Map uses an object as a key, you will have to remove it from the Map to make it eligible for the Garbage Collection.  The other solution is to use the WeakMap; they are better suitable for the Garbage Collection.

In the context of Garbage Collection, Some of the characteristics of the WeakMaps are,

  1. It takes only objects as the key
  2. Objects are held weakly in the map
  3. If the reference of the object is removed, it is available for the GC and will also be deleted from the map
  4. If the object is garbage collected, the WeakMap will have no reference for it.


You can use a WeakMap almost in the same way as a Map. However, keep in mind that all the methods of the Map are not available with the WeakMap.  A WeakMap can be created, as shown below:

var z = new WeakMap();
var x  = { id : 1};
    y  = { id : 1};
    m  = { id:1 };


console.log(z.has(x)); // true 
console.log(z.has(y)); // true  
console.log(z.has(m)); // false 


Keep in mind that the WeakMap does not have methods such as:

  • values()
  • size()
  • clear()
  • keys()
  • entries()

If you perform these operations on the WeakMap, JavaScript will throw an error.


As you learned in this post that the Map object makes it simpler to work with a key/value pair in JavaScript. It has a rich API and should be used over an object.  I hope you like this post. Thanks for reading.

For any training or consulting need to reach me at or follow me on twitter @debug_mode, or if you prefer to let us connect on LinkedIn

3 responses to “Simplifying Maps in the JavaScript”

  1. […] I have written another post detailing about Maps in JavaScript here […]

  2. Our team doesn’t really use Maps too often. Regardless, I still try to make sure I have a solid understanding of them. This is one of the most well thought out and detailed explanations I’ve seen. Cheers!

  3. Dhananjay Kumar , Microsoft MVP , Trainer and Consultant


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at