Interesting Facts About Map in JavaScript
Last Updated :
20 Jan, 2025
JavaScript Map is used to store the data of key-value pairs. It can be used to store any type of value including objects and primitive data types. It is iterable which is the main reason we can manipulate it according to the need.
Map Internally Uses Hash Table
JavaSctipt Map internally uses Hashing that makes time complexities of operations like search, insert and delete constant or O(1) on average. It is useful for operations like counting frequencies, maintaining dictionaries, and storing key-based objects.
Map vs. Objects: The Key Differences
Unlike objects, Map allows any data type as a key, not just strings and symbols. Map maintains insertion order and allows iteration in insertion order. Maps also have methods for operations on elements and property to get size.
JavaScript
let m = new Map();
m.set('name', 'GFG');
m.set(1, 'JS');
console.log(m);
console.log(m.size);
console.log(m.get('name'));
OutputMap(2) { 'name' => 'GFG', 1 => 'JS' }
2
GFG
Keys Can Be Any Data Type
One of the most powerful features of Map is its flexibility in terms of keys. In contrast to regular objects, which only support strings or symbols as keys, a Map can accept any type of value—such as numbers, objects, arrays, or even functions—as keys. This makes Map incredibly versatile for handling dynamic and complex data structures.
JavaScript
const m = new Map();
m.set(1, 'one');
m.set([1, 2], 'array as a key');
m.set({ name: 'GFG' }, 'object as a key');
console.log(m.get(1));
console.log(m.get([1, 2]));
Maps Preserve Order of Keys
When you iterate through a Map, the order of keys is always preserved. This makes Map a great choice when the order of insertion matters. This behavior is in contrast to regular objects, where the order of keys may not always be guaranteed, especially for numerical keys.
JavaScript
const m = new Map();
m.set('a', 1);
m.set('b', 2);
m.set('c', 3);
for (let [k, v] of m) {
console.log(`${k}: ${v}`);
}
You Can Check the Size of a Map Easily
With objects, you often have to use Object.keys() or other methods to get the number of properties. However, with a Map, you can simply use the size property, which directly returns the number of entries in the map. This makes it much simpler to manage and interact with Map objects when you need to know how many entries you have.
JavaScript
const m = new Map();
m.set('name', 'GFG');
m.set('Rank', 1);
console.log(m.size);
Maps Allow Efficient Lookups
One of the best features of Map objects is their ability to perform constant-time (O(1)) lookups. Whether you are adding or retrieving data, operations on a Map are very fast, even with a large number of entries. This is a significant performance improvement over objects, especially when dealing with large datasets or frequent operations.
JavaScript
const m = new Map();
m.set('name', 'GFG');
m.set('Rank', 1);
console.log(m.get('name'));
The delete() and clear() Methods
You can remove entries from a Map using the delete() method, which only removes the specified key-value pair. If you want to clear the entire Map, the clear() method does that efficiently. This is much simpler than working with objects, where you would need to manually delete properties.
JavaScript
const m = new Map();
m.set('name', 'GFG');
m.set('Rank', 1);
m.delete('Rank');
console.log(m.size);
m.clear();
console.log(m.size);
You Can Chain Methods in Map
Similar to other modern JavaScript data structures, Map allows for method chaining. Many of its methods return the Map itself, which makes it easy to chain operations.
JavaScript
const m = new Map();
m.set('a', 1).set('b', 2).set('c', 3);
console.log(m.size);
Map Supports Iteration
Map objects are iterable, which means you can loop through the entries using for...of, forEach(), or other iteration methods. This is convenient when you need to process the key-value pairs of the map.
JavaScript
const m = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of m) {
console.log(`${key}: ${value}`);
}
WeakMap: A Specialized Version of Map
In addition to the standard Map, JavaScript also provides a WeakMap, which is similar but with one key difference: it holds weak references to its keys. This means that if there are no other references to the key object, it can be garbage collected, which can be useful for memory management in certain applications.
JavaScript
let obj = { name: 'GFG' };
const WM = new WeakMap();
WM.set(obj, 'User');
console.log(WM.get(obj));
obj = null;
You Can Serialize a Map
While regular objects can easily be serialized using JSON.stringify(), Map requires a bit more work. To serialize a Map, you can convert it to an array of key-value pairs first.
JavaScript
const m = new Map([['a', 1], ['b', 2]]);
const s = JSON.stringify([...m]);
console.log(s)
Map and Object Prototypes
Unlike regular objects, which inherit properties from Object.prototype, Map does not have any default inherited properties. This makes Map a safer choice when working with dynamic keys, as it prevents unexpected behavior.
JavaScript
const m = new Map();
m.set('toString', 'GFG');
console.log(m.get('toString'));
Similar Reads
JavaScript Index inside map() Function In JavaScript, the map() functionâs callback provides an optional second parameter, the index, representing the current element's position in the array. This index starts at 0 and increments for each element, allowing access to each itemâs position during iteration.Syntax:array.map(function(currente
3 min read
How is a JavaScript Hash Map Implemented? A HashMap (also known as a dictionary or hash table in other programming languages) is a collection of key-value pairs Each key in the HashMap is unique, and each key maps to a value. The HashMap allows you to retrieve, update, or delete values by using the associated key.In JavaScript, the Map obje
5 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, the
4 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]); Pa
5 min read
JavaScript Map() Constructor The Map() constructor is used to create Map objects in JavaScript. The map is a data structure that stores elements as a key, value pair.Syntax:new Map()new Map(iterable)Parameters:iterable: An iterable object used for iterating through elements, stored as a key, value pair.Return value:A new Map ob
3 min read