JavaScript `Map` – A Detailed Guide
The Map object in JavaScript is a built-in data structure that stores key-value pairs where the keys can be of any data type, and the values can be any valid JavaScript type. Unlike objects, Map allows any type of key (including objects, functions, and primitives).
1. What is a Map?
A Map is an object that stores key-value pairs, where both the keys and the values can be any data type. It is a more powerful and flexible alternative to using objects for key-value storage.
Key Characteristics of Map:
- Key-Value Pair storage.
- The order of insertion is preserved.
- The key type is not limited to strings or symbols (it can be any value).
- Provides efficient search, insertion, and deletion operations.
2. Creating a Map
You can create a Map using the new Map() constructor. You can also initialize it with key-value pairs in an array-like structure.
Example: Creating a Map
const myMap = new Map();
console.log(myMap); // Output: Map(0) {}
Initializing with Key-Value Pairs:
const myMap = new Map([
['name', 'Alice'],
['age', 25],
['city', 'New York']
]);
console.log(myMap); // Output: Map(3) { 'name' => 'Alice', 'age' => 25, 'city' => 'New York' }
3. Basic Operations on Map
JavaScript Map provides several methods for adding, deleting, and accessing key-value pairs.
a) Adding Elements – set()
Use .set(key, value) to add key-value pairs to the Map:
const myMap = new Map();
myMap.set('name', 'Bob');
myMap.set('age', 30);
console.log(myMap); // Output: Map(2) { 'name' => 'Bob', 'age' => 30 }
b) Accessing Values – get()
Use .get(key) to retrieve the value for a specific key:
console.log(myMap.get('name')); // Output: 'Bob'
console.log(myMap.get('age')); // Output: 30
console.log(myMap.get('city')); // Output: undefined (if key doesn't exist)
c) Checking if a Key Exists – has()
Use .has(key) to check if a specific key exists in the Map:
console.log(myMap.has('name')); // Output: true
console.log(myMap.has('city')); // Output: false
d) Deleting Elements – delete()
Use .delete(key) to remove a key-value pair:
myMap.delete('age');
console.log(myMap); // Output: Map(1) { 'name' => 'Bob' }
e) Getting the Number of Elements – size
Use .size to get the number of key-value pairs:
console.log(myMap.size); // Output: 1
f) Clearing All Elements – clear()
Use .clear() to remove all key-value pairs:
myMap.clear();
console.log(myMap); // Output: Map(0) {}
4. Iterating Over a Map
You can iterate over the Map using different methods, such as forEach(), for...of, or specific iterator methods.
a) Using forEach()
The .forEach() method allows you to loop through the Map and access both the key and value:
const myMap = new Map([['name', 'Alice'], ['age', 25]]);
myMap.forEach((value, key) => {
console.log(key, value);
});
// Output:
// name Alice
// age 25
b) Using for...of Loop
You can also iterate over a Map with the for...of loop:
for (let [key, value] of myMap) {
console.log(key, value);
}
// Output:
// name Alice
// age 25
c) Using .keys(), .values(), .entries()
You can use the iterator methods .keys(), .values(), and .entries() to access specific parts of the Map.
console.log([...myMap.keys()]); // Output: ['name', 'age']
console.log([...myMap.values()]); // Output: ['Alice', 25]
console.log([...myMap.entries()]); // Output: [['name', 'Alice'], ['age', 25]]
5. Converting Between Map and Other Data Structures
a) Convert Map to an Array
You can easily convert a Map to an array using the spread operator (...) or Array.from().
const mapArray = [...myMap];
console.log(mapArray); // Output: [['name', 'Alice'], ['age', 25]]
Or using Array.from():
const mapArrayFrom = Array.from(myMap);
console.log(mapArrayFrom); // Output: [['name', 'Alice'], ['age', 25]]
b) Convert an Array of Arrays to a Map
You can create a Map from an array of arrays, where each inner array represents a key-value pair.
const arr = [['name', 'John'], ['age', 28]];
const myMapFromArr = new Map(arr);
console.log(myMapFromArr); // Output: Map(2) { 'name' => 'John', 'age' => 28 }
6. Practical Use Cases of Map
a) Storing Object References as Keys
Since Map allows any data type as a key, you can store object references as keys.
const obj1 = { id: 1 };
const obj2 = { id: 2 };
const myMap = new Map();
myMap.set(obj1, 'Object 1');
myMap.set(obj2, 'Object 2');
console.log(myMap.get(obj1)); // Output: 'Object 1'
console.log(myMap.get(obj2)); // Output: 'Object 2'
b) Counting Occurrences of Items
You can use a Map to count occurrences of items in an array.
const items = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'];
const itemCount = new Map();
items.forEach(item => {
itemCount.set(item, (itemCount.get(item) || 0) + 1);
});
console.log(itemCount); // Output: Map(3) { 'apple' => 2, 'banana' => 3, 'orange' => 1 }
c) Storing Unique Items
You can use a Map to track unique items by using an object or array as a key.
const uniqueItems = new Map();
const user = { name: 'John' };
uniqueItems.set(user, 'User1');
console.log(uniqueItems.get(user)); // Output: 'User1'
7. Differences Between Map and Object
| Feature | Map | Object |
| Key Type | Any type (including objects, functions) | String or Symbol only |
| Order of Keys | Maintains insertion order | Does not guarantee order |
| Iteration Methods | .forEach(), .keys(), .values(), .entries() | for...in loop |
| Performance for Key Lookups | Faster (O(1)) | Slower (O(n)) |
| Default Behavior | No default properties like toString | Has default properties like toString, hasOwnProperty, etc. |
8. Summary
- A
Mapis a key-value data structure that can store any data type as both the key and value. - Methods like
.set(),.get(),.has(),.delete(), and.sizeprovide an efficient way to manipulate and retrieve values. Mappreserves the order of insertion and provides flexible iteration methods.- Useful for storing key-value pairs where keys are not limited to strings.