The Wayback Machine - https://web.archive.org/web/20240930191312/https://www.geeksforgeeks.org/javascript-map/
Open In App

JavaScript Map

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The JavaScript Map object holds key-value pairs and preserves the original insertion order. It supports any value, including objects and primitives, as keys or values. This feature allows for efficient data retrieval and manipulation, making Map a versatile tool for managing collections.

On iterating a map object 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 }

Steps to Create a Map

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

Examples of JavaScript Map

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'
}

Methods of JavaScript Map

  • set(key, value): Adds or updates an element with a specified key and value.
  • get(key): Returns the value associated with the specified key.
  • has(key): Returns a boolean indicating whether an element with the specified key exists.
  • delete(key): Removes the element with the specified key.
  • clear(): Removes all elements from the Map.
  • size: Returns the number of key-value pairs in the Map.

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...

Advantages of Map

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.

  • Unique Keys: A key can occur only once, ensuring uniqueness within the collection.
  • Security: No default keys are stored; only what is explicitly added, making it safer.
  • Flexible Key Types: Any value (object, function, etc.) can be used as a key.
  • Order: Maintains the order of entry insertion.
  • Size Property: The size property makes it easy to retrieve the number of elements.
  • Performance: Operations on Maps can be performed efficiently.
  • Serialization and Parsing: Custom serialization and parsing support using JSON.stringify() and JSON.parse() methods.

JavaScript Maps provide a robust mechanism for handling key-value pairs, offering unique advantages over plain objects. With their secure, flexible, and efficient operations, Maps are an essential tool for modern web development. Coupled with the map() method for arrays, JavaScript offers versatile ways to manipulate and iterate over data collections effectively.

Supported Browsers

JavaScript Map – FAQs

What is a Map in JavaScript?

A Map is a built-in object that allows you to store key-value pairs. Unlike regular objects, which only allow string or symbol keys, a Map can have keys of any type, including objects, functions, and primitives.

How do you create a Map?

You can create a Map using the Map constructor.

Example: const myMap = new Map();

How do you add key-value pairs to a Map?

You can add key-value pairs to a Map using the set() method. This method takes two arguments: the key and the value.

Example: myMap.set(‘key’, ‘value’);

How do you get a value from a Map?

You can retrieve a value from a Map using the get() method. This method takes one argument, the key, and returns the associated value.

Example: myMap.get(‘key’);

How do you check if a key exists in a Map?

You can check if a key exists in a Map using the has() method. This method returns true if the key exists, and false otherwise.

Example: myMap.has(‘key’);

How do you remove a key-value pair from a Map?

You can remove a key-value pair from a Map using the delete() method. This method takes one argument, the key, and removes the associated key-value pair.

Example: myMap.delete(‘key’);



Previous Article
Next Article

Similar Reads

How to map array values without using map method in JavaScript ?
Array elements can be mapped by using looping methods in JavaScript. The map() method creates a new array with the results of the output of a function called for each array element. This can also be implemented using a for loop in JavaScript. Approach 1: For this, we can create two arrays, in which one array contains the array elements that are to
3 min read
PHP | Ds\Map map() Function
The Ds\Map::map() function of the Map class in PHP is used to apply a callback function to a Map object. This returns the result of applying the callback function to each value present on the map. The function does not update the values in the original map, instead, it just returns the result of the updates without affecting the original values. Sy
2 min read
Create a Map with Google Map Api using React-Native
In this project, we'll explore how to integrate Google Maps into a React Native application. We'll create a dynamic map that allows users to view their current location and interact with markers on the map. This project aims to provide a practical guide for developers looking to incorporate maps into their mobile applications using React Native. Ou
3 min read
What is image map & how to map the image in HTML ?
In this article, we will discuss an image map in HTML, along with understanding its implementation through examples. An Image Map refers to the clickable image having a clickable area that can be used to navigate to the various links to other web pages or the specific section of the same web page. The <map> tag can be used to define the image
2 min read
Implement polyfill for Array.prototype.map() method in JavaScript
In this article, we will learn how to implement a polyfill for an Array.prototype.map() method in JavaScript. What is a polyfill? A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or because the new version of the br
3 min read
JavaScript Array map() Method
JavaScript Array map() Method method creates a new array with the results of a called function for every array element. This function calls the argument function once for each element of the given array in order. Syntax: // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /*
3 min read
JavaScript Map.prototype[@@iterator]() Method
Map[@@iterator]( ) method is used to make Map iterable. Map[@@iterator]( ) method returns iterator object which iterates over all code points of Map. Map[@@iterator]( ) is built-in property of Map. We can use this method by creating Map iterator. We can make Map iterator by calling the @@iterator property. In place of @@iterator, we can use Symbol.
2 min read
JavaScript typedArray.map() Method
The typedArray.map() is an inbuilt function in JavaScript which is used to create a new typedArray with the result of a provided function on each element of the given typedArray. Syntax: typedArray.map(callback) Parameters: It accepts a parameter callback function which accept some parameter which are specified below- currentValue: It is the curren
1 min read
How to create an image map in JavaScript ?
An image map is nothing but an image that is broken into various hotspots and each hotspot will take you to a different file. Hotspots are nothing but clickable areas which we create on an image by using the <area> tag. This type of map is called a client-side image map as the map is embedded in the HTML itself. Approach: Below is the step-by
3 min read
How to use map() on an array in reverse order with JavaScript ?
Given a JavaScript array and the task is to apply the map() method but on the reverse of the array efficiently. Here are a few approaches discussed. If you don't want to change the original array then you can create a shallow copy of the array after that you can perform the task. Approaches to use array.map() in reverse order:Using JavaScript array
3 min read
How to serialize a Map in JavaScript ?
In this article, we will discuss, the serialization of maps in JavaScript. Serialization is the conversion of an object or a data structure to another format that is easily transferrable on the network. In JavaScript, the format suitable for transferring is JSON string. So, we usually call the JSON.stringify() method to convert the data in our pref
2 min read
How to map, reduce and filter a Set element using JavaScript ?
The map(), reduce() and filter() are array functions that transform the array according to the applied function and return the updated array. They are used to write simple, short and clean codes for modifying an array instead of using the loops. map() method: It applies a given function on all the elements of the array and returns the updated array
2 min read
What is the difference between Map and WeakMap in JavaScript ?
In this article, we will talk about the difference between Map and WeakMap which are introduced by ES6. Javascript object supports only one key object. For supporting multiple key objects, Then Map comes on this path. Map: A Map is an unordered list of key-value pairs where the key and the value can be of any type like string, boolean, number, etc.
4 min read
How are elements ordered in a Map in JavaScript ?
In JavaScript, a new object called Map was introduced in the ES6 version. A map is a collection of elements where each element is stored in a key, value pair. Map objects can store both objects as well as primitive data types. The elements of a map are iterable. Elements are always iterated in the insertion order. The elements in a map are ordered
2 min read
JavaScript Map constructor Property
The map constructor property in JavaScript is used to return the map constructor function for the object. The function which is returned by this property is just the reference to this function, not a map containing the function's name. The JavaScript map constructor, string constructor, and boolean constructor return function Map() { [native code]
1 min read
Internal Working of Map in JavaScript
The 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. In this article, we will check the internal working of a Map in JavaScript. Internal Working of Map The Map in JavaScript allows for storing key-value pairs, providing efficient operat
3 min read
Applications of Map in JavaScript
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. Syntax: new Map([it]); Parameter: it: It is any iterable object whose value
5 min read
JavaScript Map() Constructor Property
The Javascript Map() Constructor property returns the constructor function of the map. It only returns the reference of the function and does not return the name of the function. In the JavaScript Map() constructor, it returns the function Map(){ [native code] }. Syntax: Map.constructorReturn value: Return the construction function of the Map. in t
1 min read
Map to Array in JavaScript
In this article, we will convert a Map object to an Array in JavaScript. A Map is a collection of key-value pairs linked with each other. The following are the approaches to Map to Array conversion: Methods to convert Map to ArrayUsing Spread Operator (...) and Array map() MethodUsing Array.from() MethodUsing Map.forEach() MethodApproach 1: Using S
3 min read
How to convert a plain object into ES6 Map using JavaScript ?
The task is to convert a JavaScript Object into a plain ES6 Map using JavaScript. we're going to discuss a few techniques. To understand the difference between a map and an object please go through the Map vs Object in JavaScript article. Below are the following approaches to converting a plain object into ES6 Map using JavaScript: Using map() Cons
2 min read
Set vs Map in JavaScript
In JavaScript, Set and Map are two types of objects that are used for storing data in an ordered manner. Both these data structures are used to store distinct types of data inside the same object. In Maps, the data is stored as a key-value pair whereas in Set data is a single collection of values that are unique. Let's learn about the uses of these
2 min read
JavaScript Map Reference
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. You can create a JavaScript Map by: Passing an Array to new Map()Create a M
3 min read
How to convert a Set to Map in JavaScript?
A Set is a collection of unique values. It stores only the data in the form of values while a Map can store the data in the form of key-value pairs. These are the different ways of converting a Set to a Map in JavaScript: Table of Content Using the Array.from() methodUsing the Spread Operator with map() methodUsing the reduce() methodUsing the forE
3 min read
How to convert a Map into a Set in JavaScript?
Map and Set in JavaScript are special kind of data structures that holds only the unique data. There will be no duplicate data stored in them. Maps store data in the form of key-value pairs, while the Sets store in the form of values only. In some scenarios, you need to convert a Map into a Set, there you can use the below methods for the conversio
4 min read
What is the use of the Map Function in JavaScript ?
The map function is used to transform elements in an array. It is a higher-order function that takes a callback function as an argument and applies that function to each element of the array, creating a new array with the results. The primary goal map is to perform a specific operation on each element of an array and generate a new array based on t
1 min read
What are the Differences Between Map and Object in JavaScript ?
Maps and Objects both are used to store data in the form of key-value pairs although both of these data types allow you to get, delete, and update the values stored in them. Also, objects have been used as maps. But, there are many differences between them as listed in the below table: Map Objects It provides a size property to get the size of the
1 min read
What is the use of the Map.prototype.clear method in JavaScript Maps ?
In JavaScript, the Map.prototype.clear method is used to remove all key-value pairs from a Map, effectively making the Map empty. It does not take any arguments and does not return any value. Syntax:myMap.clear();myMap: The Map from which you want to remove all key-value pairs.Example: Here, a map object “myMap” has been created with a single [key,
1 min read
What is the use of the Map.prototype.keys method in JavaScript Maps ?
In JavaScript, the Map.prototype.keys method is used to get an iterator object that contains the keys of a Map. The iterator object follows the iterable protocol, allowing you to loop through the keys using methods like next() or using a for...of loop. Syntax:myMaps.key();myMap: The Map for which you want to obtain an iterator for its keys.Example:
1 min read
How to Check the Size of a JavaScript Map ?
To check the size (number of key-value pairs) of a Map in JavaScript, you can use the size property. The size property is a property of the Map object that returns the number of elements in the Map. Example: Here, mapSize will be equal to 3 because there are three key-value pairs in the Map. C/C++ Code let myMap = new Map(); myMap.set('key1', 'valu
1 min read
How to Create an Empty Map in JavaScript ?
In JavaScript, you can create an empty Map using the Map constructor. whenever we initialize any map it is empty at first and we need to declare the key-value pair inside the map constructor to construct the map having values. Syntax:let emptyMap = new Map();Example: Here, initialMap is a Map that has been initialized with key-value pairs. let init
1 min read