JavaScript Map is a powerful data structure used to store key-value pairs, offering more flexibility than traditional objects. It allows keys of any data type, making it highly versatile.
- A Map can use any value as a key (objects, functions, primitives), unlike regular objects.
- It preserves insertion order, ensuring predictable iteration.
- Maps come with built-in methods like set(), get(), has(), and delete() for efficient data management.
1. Internal Working of Map
JavaScript Maps are typically implemented using hash-based or other optimized structures depending on the engine, providing average O(1) time complexity for insert, search, and delete operations.
2. 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, allowing predictable iteration. Maps also have methods for operations on elements and property to get size.
let m = new Map();
m.set('name', 'GFG');
m.set(1, 'JS');
console.log(m);
console.log(m.size);
console.log(m.get('name'));
3. 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.
const arr = [1, 2];
const m = new Map();
m.set(arr, 'array as a key');
console.log(m.get(arr));
4. Maps Preserve Order of Keys
Map preserves the insertion order of keys, so elements are iterated in the same order they were added. This makes Map a good choice when the order of elements matters.
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}`);
}
5. 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.
const m = new Map();
m.set('name', 'GFG');
m.set('Rank', 1);
console.log(m.size);
6. 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.
const m = new Map();
m.set('name', 'GFG');
m.set('Rank', 1);
console.log(m.get('name'));
7. 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.
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);
8. 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.
const m = new Map();
m.set('a', 1).set('b', 2).set('c', 3);
console.log(m.size);
9. 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.
const m = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of m) {
console.log(`${key}: ${value}`);
}
10. 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.
let obj = { name: 'GFG' };
const WM = new WeakMap();
WM.set(obj, 'User');
console.log(WM.get(obj));
obj = null;
11. 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.
const m = new Map([['a', 1], ['b', 2]]);
const s = JSON.stringify([...m]);
console.log(s)
12. Map and Object Prototypes
Unlike regular objects that inherit properties from Object.prototype, Map avoids accidental key collisions with inherited properties, making it safer for dynamic key-value storage.
const m = new Map();
m.set('toString', 'GFG');
console.log(m.get('toString'));