What is a JavaScript Map?
A Map is a collection of elements where each element is stored as a key-value pair. Keys and values can be of any data type.
Key Features of Maps:
- Order Preservation: Maps maintain the order of insertion.
- Key Flexibility: Keys can be strings, objects or any data type.
- Iteration Support: Maps are easy to iterate using loops or iterators.
Creating a Map:
const map = new Map();
Common Methods and Properties of Maps
- set(key, value)
- get(key)
- has(key)
- delete(key)
- clear()
- size (property, not a method)
- keys()
- values()
- entries()
- forEach()
1. set(key, value) Method
The set() method adds or updates a key-value pair in the Map.
Syntax:
map.set(key, value);
Example:
const map = new Map();
map.set('name', 'John');
map.set(1, 'One');
map.set(true, 'Boolean Value');
console.log(map);
// Output: Map(3) { 'name' => 'John', 1 => 'One', true => 'Boolean Value' }
2. get(key) Method
The get() method retrieves the value associated with a specific key.
Syntax:
map.get(key);
Example:
const map = new Map();
map.set('name', 'Alice');
console.log(map.get('name')); // Output: Alice
console.log(map.get('age')); // Output: undefined
3. has(key) Method
The has() method checks if a key exists in the Map. It returns true if the key is found, otherwise false.
Syntax:
map.has(key);
Example:
const map = new Map([['name', 'Bob'], ['age', 25]]);
console.log(map.has('name')); // Output: true
console.log(map.has('gender')); // Output: false
4. delete(key) Method
The delete() method removes a specific key-value pair from the Map. It returns true if the pair was removed and false otherwise.
Syntax:
map.delete(key);
Example:
const map = new Map([['name', 'Bob'], ['age', 25]]);
map.delete('name');
console.log(map); // Output: Map(1) { 'age' => 25 }
5. clear() Method
The clear() method removes all key-value pairs from the Map.
Syntax:
map.clear();
Example:
const map = new Map([['name', 'Alice'], ['age', 30]]);
map.clear();
console.log(map); // Output: Map(0) {}
6. size Property
The size property returns the number of key-value pairs in the Map.
Syntax:
map.size;
Example:
const map = new Map([['a', 1], ['b', 2]]);
console.log(map.size); // Output: 2
Iteration Methods
Maps provide several methods for iterating over keys, values or key-value pairs:
- keys(): Returns an iterator of all keys.
- values(): Returns an iterator of all values.
- entries(): Returns an iterator of [key, value] pairs.
- forEach(): Executes a callback function for each key-value pair.
Examples:
Using keys()
const map = new Map([['a', 1], ['b', 2]]);
for (const key of map.keys()) {
console.log(key);
}
// Output:
// a
// b
Using values()
for (const value of map.values()) {
console.log(value);
}
// Output:
// 1
// 2
Using entries()
for (const [key, value] of map.entries()) {
console.log(`${key}: ${value}`);
}
// Output:
// a: 1
// b: 2
Using forEach()
map.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
// Output:
// a: 1
// b: 2
Practical Use Cases of Maps
Storing User Information:
const userInfo = new Map();
userInfo.set('name', 'Alice');
userInfo.set('email', 'alice@example.com');
console.log(userInfo.get('email')); // Output: alice@example.com
Tracking Element Frequencies:
const arr = ['apple', 'banana', 'apple', 'orange'];
const freqMap = new Map();
arr.forEach(item => {
freqMap.set(item, (freqMap.get(item) || 0) + 1);
});
console.log(freqMap);
// Output: Map(3) { 'apple' => 2, 'banana' => 1, 'orange' => 1 }
Implementing Caches:
const cache = new Map();
function fetchData(key) {
if (cache.has(key)) {
console.log('From Cache:', cache.get(key));
return cache.get(key);
} else {
const data = `Data for ${key}`;
cache.set(key, data);
console.log('Fetched:', data);
return data;
}
}
fetchData('user1');
fetchData('user1');
// Output:
// Fetched: Data for user1
// From Cache: Data for user1