JavaScript Map

Map

Map is introduced in JavaScript with ECMAScript 6.

A map is simple key-value pair.

Any value (both objects and primitive values) may be used as either a key or a value.
 

Creating a Map

We can create a new map using syntax : new Map() or new Map([iterable])

Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays). Each key-value pair is added to the new Map.
 
We can use get() and set() methods to get and set elements in a map.

Here is an example of creating a map and adding elements to it.

var capital = new Map();
capital.set("India", "Delhi");
capital.set("Japan", "Tokyo");
capital.set("China", "Beijing");
alert(capital.get("Japan"));

 

Iterating a Map

We can iterate elements of a map in the order of their insertion.

var capital = new Map();
capital.set("India", "Delhi");
capital.set("Japan", "Tokyo");
capital.set("China", "Beijing");

for (var [key, value] of capital) {
  alert("Capital of " + key + " is " + value);
}

 

map console log

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags