Open In App
Related Articles

JavaScript Map

Improve Article
Improve
Save Article
Save
Like Article
Like

JavaScript map is a collection of elements where each element is stored as a Key, value pair. Map objects can hold both objects and primitive values as either key or value.

When we iterate over the map object it returns the key, and value pair in the same order as inserted. Map() constructor is used to create Map in JavaScript.

JavaScript Map has a property that represents the size of the map.

Example:

Input:
let map1 = new Map([
[1 , 10], [2 , 20] ,
[3, 30],[4, 40]
]);

console.log("Map1: ");
console.log(map1);
Output:
// Map1:
// Map(4) { 1 => 10, 2 => 20, 3 => 30, 4 => 40 }

Map object provided by ES6. A key of a Map may occur once, which will be unique in the map’s collection. There are slight advantages to using a map rather than an object.

  • Accidental Keys & Security: No default keys are stored, only contain what’s explicitly put into them. Because of that, it’s safe to use.
  • Key Types & Order: It can be any value as a key function, object anything. And the order is straightforward way in the order of entry insertion.
  • Size: Because of the size property a map can be easily retrieved.
  • Performance: Any operation can be performed on math so easily in a better way.
  • Serialization and parsing: We can create our own serialization and parsing support for Map by using JSON.stringify() and JSON.parse() methods.

Steps to Create a Map:

  • Passing an Array to new Map()
  • Create a Map and use Map.set()

new Map():

In this we use new Map() constructor,

Example: In this example, a Map named prices is created to associate product names with their respective prices, allowing for efficient retrieval and management of price information.

// Creating a Map for product prices
const prices = new Map([
["Laptop", 1000],
["Smartphone", 800],
["Tablet", 400]
]);

Map.set():

You can add elements to a Map with the set() method.

Example: In this example, the Map.set() method is employed to add product prices to the Map named prices.

// Creating a Map for product prices
const prices = new Map();
// Using Map.set() to add product prices
prices.set('Laptop', 1000);
prices.set('Smartphone', 800);
// The Map now contains { 'Laptop' => 1000, 'Smartphone' => 800 }

Example 1: In this example, we will create a basic map object

Javascript




let map1 = new Map([
    [1, 2],
    [2, 3],
    [4, 5]
]);
 
console.log("Map1");
console.log(map1);
 
let map2 = new Map([
    ["firstname", "sumit"],
    ["lastname", "ghosh"],
    ["website", "geeksforgeeks"]
]);
 
console.log("Map2");
console.log(map2);


Output: 

Map1
Map(3) {1 => 2, 2 => 3, 4 => 5}
Map2
Map(3) {'firstname' => 'sumit', 'lastname' => 'ghosh', 'website' => 'geeksforgeeks'}

Example 2: This example adds elements to the map using set() method.

Javascript




let map1 = new Map();
map1.set("FirstName", "Shobhit");
map1.set("LastName", "Sharma");
map1.set("website", "GeeksforGeeks");
 
console.log(map1);


Output:

Map(3) {'FirstName' => 'Shobhit', 'LastName' => 'Sharma', 'website' => 'GeeksforGeeks'}

Example 3: This example explains the use of Map methods like has(), get(), delete(), and clear().

Javascript




let map1 = new Map();
 
map1.set("first name", "sumit");
map1.set("last name", "ghosh");
map1.set("website", "geeksforgeeks")
    .set("friend 1","gourav")
    .set("friend 2","sourav");
 
console.log(map1);
     
console.log("map1 has website ? "+
                    map1.has("website"));
 
console.log("map1 has friend 3 ? " +
                    map1.has("friend 3"));
 
console.log("get value for key website "+
                    map1.get("website"));
 
console.log("get value for key friend 3 "+
                    map1.get("friend 3"));
console.log("delete element with key website "
                    + map1.delete("website"));
     
console.log("map1 has website ? "+
                    map1.has("website"));
 
console.log("delete element with key website " +
                    map1.delete("friend 3"));
 
map1.clear();
 
console.log(map1);


Output: 

Map(5) {'first name' => 'sumit', 
'last name' => 'ghosh',
'website' => 'geeksforgeeks',
'friend 1' => 'gourav',
'friend 2' => 'sourav'}
map1 has website ? true
map1 has friend 3 ? false
get value for key website geeksforgeeks
get value for key friend 3 undefined
delete element with key website true
map1 has website ? false
delete element with key website false
Map(0) {size: 0}

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari
  • Internet Explorer

We have a complete list of Javascript Map methods, to check them please go through the Javascript Map Reference article.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 22 Nov, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials