Open In App

Interesting Facts About Map in JavaScript

Last Updated : 20 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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'));  

Output
Map(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]));  

Output
one
undefined

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}`);
}

Output
a: 1
b: 2
c: 3

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); 

Output
2

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'));  

Output
GFG

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);  

Output
1
0

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);  

Output
3

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}`);
}

Output
a: 1
b: 2
c: 3

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;  

Output
User

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)

Output
[["a",1],["b",2]]

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'));  

Output
GFG

Next Article

Similar Reads