Map in JavaScript

31 May, 2022
In this article, we would be discussing Map object provided by ES6. Map is a collection of elements where each element is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, value pair in the same order as inserted.
Syntax: 
new Map([it])

Parameter:
it - It is any iterable object whose values are stored as 
     key, value pair,
     If the parameter is not specified then a new map is created 
     is Empty

Returns:
A new Map object
Now lets create some Map using the Map object 
Javascript
// map1 contains// 1 => 2// 2 => 3// 4 -> 5var map1 = new Map([[1 , 2], [2 ,3 ] ,[4, 5]]); console.log("Map1");console.log(map1); // map2 contains// firstname => sumit// lastname => ghosh// website => geeksforgeeksvar map2 = new Map([["firstname" ,"sumit"],        ["lastname", "ghosh"], ["website", "geeksforgeeks"]]); console.log("Map2");console.log(map2);  // map3 contains// Whole number => [1, 2, 3, 4]// Decimal number => [1.1, 1.2, 1.3, 1.4]// Negative number => [-1, -2, -3, -4]var map3 = new Map([["whole numbers", [1 ,2 ,3 ,4]],            ["Decimal numbers" , [1.1, 1.2, 1.3, 1.4]],            ["negative numbers", [-1, -2, -3, -4]]]); console.log("Map3");console.log(map3);  // map 4 contains// storing arrays both as key and value// "first name ", "Last name" => "sumit", "ghosh"// "friend 1", "sourav" => "friend 2", "gourav"var map4 = new Map([[["first name", "last name"],            ["sumit", "ghosh"]],            [["friend 1", "friend 2"],            ["sourav","gourav"]]]); console.log("Map4");console.log(map4);
Output: 
Properties: 
Map.prototype.size – It returns the number of elements or the key-value pairs in the map.
 Methods:  
1. Map.prototype.set() – It adds the key and value to the Map Object. 
Syntax: 
map1.set(k, v);

Parameters:
k - Key of the element to be added to the Map
v - value of the element to be added to the Map

Returns:
It returns a Map object
2. Map.prototype.has() – It return a boolean value depending on whether the specified key is present or not.
Syntax: 
map1.has(k);

Parameters:
k - Key of the element to checked 

Returns:
true if the element with the specified key is present 
or else returns false. 
3. Map.prototype.get() – It returns the value of the corresponding key.
Syntax: 
map1.get(k);

Parameters:
k - Key, whose value is to be returned

Returns:
The value associated with the key, if it is present 
in Map, otherwise returns undefined
4. Map.prototype.delete() – It delete’s both the key as well as a value from the map. 
Syntax: 
map1.delete(k);

Parameters:
k - Key which is to be deleted from the map 

Returns:
true if the value is found and deleted from 
the map otherwise, it returns false
5. Map.prototype.clear() – Removes all the elements from the Map object.
Syntax: 
map1.clear();

Parameters:
No parameters

Returns:
undefined
Lets use all the methods described above: 
Example: 
Javascript
// Using Map.prototype.set(k, v)// creating an empty mapvar map1 = new Map(); // adding some elements to the mapmap1.set("first name", "sumit");map1.set("last name", "ghosh");map1.set("website", "geeksforgeeks")    .set("friend 1","gourav")    .set("friend 2","sourav"); // map1 contains// "first name" => "sumit"// "last name" => "ghosh"// "website" => "geeksforgeeks"// "friend 1" => "gourav"// "friend 2" => "sourav"console.log(map1);     // Using Map.prototype.has(k) // returns trueconsole.log("map1 has website ? "+                    map1.has("website")); // return falseconsole.log("map1 has friend 3 ? " +                    map1.has("friend 3"));      // Using Map.prototype.get(k) // returns geeksforgeeksconsole.log("get value for key website "+                    map1.get("website")); // returns undefinedconsole.log("get value for key friend 3 "+                    map1.get("friend 3")); // Using Map.prototype.delete(k) // removes key "website" and its value from// the map// it prints the value of the keyconsole.log("delete element with key website "                    + map1.delete("website"));     // as the value is deleted from// the map hence it returns falseconsole.log("map1 has website ? "+                    map1.has("website")); // returns false as this key is not in the listconsole.log("delete element with key website " +                    map1.delete("friend 3"));  // Using Map.prototype.clear()// removing all values from map1map1.clear(); // map1 is emptyconsole.log(map1);
Output: 
6. Map.prototype.entries() – It returns an iterator object that contains key/value pair for each element present in the Map object. 
Syntax: 
map1.entries();

Parameters:
No parameters

Returns:
It returns an iterator object 
7. Map.prototype.keys() – It returns an iterator object which contains all the keys present in the Map Object. 
Syntax: 
map1.keys();

Parameters:
No parameter

Returns:
An iterator object 
8. Map.prototype.values() – It returns an iterator object which contains all the values present in the Map Object. 
Syntax: 
map1.values();

Parameters:
No parameter

Returns: 
An iterator object 
Lets use all the methods described above: 
Example: 
Javascript
// creating an empty mapvar map1 = new Map(); // adding some elements to the mapmap1.set("first name", "sumit");map1.set("last name", "ghosh");map1.set("website", "geeksforgeeks")    .set("friend 1","gourav")    .set("friend 2","sourav");  // Using Map.prototype.entries() // getting all the entries of the mapvar get_entries = map1.entries();  // it prints// ["first name", "sumit"]// ["last name", "ghosh"]// ["website", "geeksforgeeks"]// ["friend 1", "gourav"]// ["friend 2", "sourav"]console.log("----------entries---------");for(var ele of get_entries)console.log(ele); // Using Map.prototype.keys() // getting all the keys of the mapvar get_keys = map1.keys(); // it prints// "first name", "last name",// "website", "friend 1", "friend 2"console.log("--------keys----------");for(var ele of get_keys)console.log(ele); // Using Map.prototype.values() // getting all the values of the mapvar get_values = map1.values(); // it prints all the values// "sumit", "ghosh", "geeksforgeeks"// "gourav", "sourav"console.log("----------values------------");for(var ele of get_values)console.log(ele);
Output: 
9. Map.prototype.forEach() – It executes the callback function once for each key/value pair in the Map, in the insertion order. 
Syntax: 
map1.forEach(callback,  [thisArgument]);

Parameters:
callback - It is a function that is to be executed for each element of the Map.
thisargument - Value to be used as this when executing the callback.

Returns:
undefined
The callback function is provided with three parameters as follows: 
the element key
the element value
the Map object to be traversed
Example:
Javascript
// using Map.prototype.forEach()// creating an empty mapvar map1 = new Map();   // adding some elements to the map map1.set("first name", "sumit");map1.set("last name", "ghosh");map1.set("website", "geeksforgeeks")    .set("friend 1", "gourav")    .set("friend 2", "sourav");   // Declaring a call back function// we are using only one parameter value// so it will ignore other two .function printOne(values) {   console.log(values);}   // It prints value of all the element // of the setconsole.log("-----one parameter-----");map1.forEach(printOne);   // Declaring a call back function// we are using two parameter value// so it will ignore last one function printTwo(values, key) {   console.log(key + "  " + values);}   // As key and values are same in set// so it will print values twiceconsole.log("-----two parameter-----");map1.forEach(printTwo);   // Declaring a call back function// we are using all three parameter valuefunction printThree(values, key, map) {   // it will print key and value    // and the set object   console.log(key + "  " + values);   console.log(map);}   // It prints key and value of each // element and the entire Map objectconsole.log("-----three parameter-----");map1.forEach(printThree);
Output:
Note: In the above example we use a simple callback function which just print an element in the console, it can be designed to perform any complex operation as per requirement.
10. Map.prototype[@@iterator]() – It returns an Map iterator function which is entries() method of Map object by default. 
Syntax: 
map1[Symbol.iterator]

Parameters:
No parameters

Returns:
Returns an map iterator object and it is 
entries() by default
Example: 
Javascript
// using Map.prototype[@@iterator]()// creating an empty mapvar map1 = new Map(); // adding some elements to the mapmap1.set("first name", "sumit");map1.set("last name", "ghosh");map1.set("website", "geeksforgeeks")    .set("friend 1", "gourav")    .set("friend 2", "sourav"); // By default this method returns the// same iterator object return by entries methodsvar getit = map1[Symbol.iterator](); // it prints// ["first name", "sumit"]// ["last name", "ghosh"]// ["website", "geeksforgeeks"]// ["friend 1", "gourav"]// ["friend 2", "sourav"]for(var elem of getit)    console.log(elem);
Output: 
11. Map used to iterate over arrays
Syntax:
arr.map(function(value,index){})

Parameters: 
value = array element
           index = index of array
           
Return:
Modified valueo of elements
Example:
Javascript
let arr = [1,2,3,4,5] let arr1 = []; //iterate over array and store in arr1arr1 = arr.map((value,idx)=>{    console.log("value "+value,"idx "+idx);    return value*2;}) console.log();//original arrayconsole.log("arr= "+arr);//modified arrayconsole.log("arr1= "+arr1);
Output:
 
Note:- We can create a user define iterable rather than using the default one.
Reference: 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map 
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Akanksha_Rai
surindertarika1234
varshagumber28
rajeev0719singh
sagar0719kumar
prachisoda1234
surbhikumaridav
sweetyty
JavaScript-ES
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
How do you run JavaScript script through the Terminal?
JavaScript | console.log() with Examples