What is JavaScript Map Methods?
JavaScript Map methods are essential for managing key-value pairs in a Map object. They allow developers to add, retrieve, modify or delete entries efficiently. With their flexibility and simplicity, these methods provide a structured approach to handling data collections in JavaScript.
Overview of JavaScript Map Methods
Here is a list of commonly used JavaScript Map methods:
- set(key, value)
- get(key)
- has(key)
- delete(key)
- clear()
- size (property, not a method)
- keys()
- values()
- entries()
- forEach()
These methods make Maps highly versatile and efficient for key-value pair manipulation.
1. set(key, value) Method
The set() method adds a key-value pair to a Map or updates the value if the key already exists.
Syntax:
map.set(key, value);
Example:
const map = new Map();
map.set('name', 'Alice');
map.set(1, 'Number Key');
map.set(true, 'Boolean Key');
console.log(map);
// Output: Map(3) { 'name' => 'Alice', 1 => 'Number Key', true => 'Boolean Key' }
2. get(key) Method
The get() method retrieves the value associated with a specific key in the Map. If the key does not exist, it returns undefined.
Syntax:
map.get(key);
Example:
const map = new Map();
map.set('color', 'blue');
console.log(map.get('color')); // Output: blue
console.log(map.get('size')); // Output: undefined
3. has(key) Method
The has() method checks whether a specific key exists in the Map. It returns true if the key is found, otherwise false.
Syntax:
map.has(key);
Example:
const map = new Map([['brand', 'Toyota'], ['year', 2024]]);
console.log(map.has('brand')); // Output: true
console.log(map.has('model')); // Output: false
4. delete(key) Method
The delete() method removes a key-value pair from the Map. It returns true if the pair was successfully deleted, otherwise false.
Syntax:
map.delete(key);
Example:
const map = new Map();
map.set('name', 'John');
console.log(map.delete('name')); // Output: true
console.log(map); // Output: Map(0) {}
5. clear() Method
The clear() method removes all key-value pairs from the Map, effectively resetting it to an empty Map.
Syntax:
map.clear();
Example:
const map = new Map([['name', 'Alice'], ['age', 25]]);
map.clear();
console.log(map); // Output: Map(0) {}
6. size Property
The size property returns the total number of key-value pairs in the Map.
Syntax:
map.size;
Example:
const map = new Map([['x', 10], ['y', 20]]);
console.log(map.size); // Output: 2
Iteration Methods in Maps
Maps provide several iteration methods for traversing keys, values, and key-value pairs.
7. keys() Method
The keys()
method returns an iterator containing all the keys in the Map.
Syntax:
map.keys();
Example:
const map = new Map([['a', 1], ['b', 2]]);
for (const key of map.keys()) {
console.log(key);
}
// Output:
// a
// b
8. values() Method
The values() method returns an iterator containing all the values in the Map.
Syntax:
map.values();
Example:
const map = new Map([['a', 1], ['b', 2]]);
for (const value of map.values()) {
console.log(value);
}
// Output:
// 1
// 2
9. entries() Method
The entries() method returns an iterator containing all [key, value] pairs in the Map.
Syntax:
map.entries();
Example:
const map = new Map([['x', 10], ['y', 20]]);
for (const [key, value] of map.entries()) {
console.log(`${key}: ${value}`);
}
// Output:
// x: 10
// y: 20
10. forEach() Method
The forEach() method executes a callback function for each key-value pair in the Map.
Syntax:
map.forEach(callbackFunction(value, key, map));
Example:
const map = new Map([['name', 'Alice'], ['age', 30]]);
map.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
// Output:
// name: Alice
// age: 30
Practical Use Cases of Map Methods
Tracking User Data:
const userData = new Map();
userData.set('name', 'John');
userData.set('email', 'john@example.com');
console.log(userData.get('email')); // Output: john@example.com
Counting Frequencies:
const arr = ['apple', 'banana', 'apple', 'orange'];
const frequency = new Map();
arr.forEach(item => {
frequency.set(item, (frequency.get(item) || 0) + 1);
});
console.log(frequency);
// Output: Map(3) { 'apple' => 2, 'banana' => 1, 'orange' => 1 }
Storing Cache Data:
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