In JavaScript, a Map is a collection of key-value pairs where each key can map to at most one value. Unlike objects, which only allow string or symbol keys, Maps allow any data type to be used as a key. This makes Maps versatile for various use cases. Here's an overview of Maps in JavaScript:
You can create a Map using the Map() constructor or the Map literal notation {}.
// Using Map constructor
const myMap = new Map();
// Using Map literal notation
const myMap2 = new Map([
['key1', 'value1'],
['key2', 'value2']
]);
Maps provide methods to add and retrieve elements:
const myMap = new Map();
myMap.set('name', 'John');
myMap.set(1, 'One');
console.log(myMap.get('name')); // Output: John
console.log(myMap.get(1)); // Output: One
You can check if a key exists in a Map and get its size:
const myMap = new Map();
myMap.set('name', 'John');
console.log(myMap.has('name')); // Output: true
console.log(myMap.size); // Output: 1
Maps provide methods to delete specific key-value pairs or clear all entries:
const myMap = new Map();
myMap.set('name', 'John');
myMap.delete('name');
console.log(myMap.has('name')); // Output: false
myMap.set('name', 'John');
myMap.set('age', 30);
myMap.clear();
console.log(myMap.size); // Output: 0
Maps are iterable, allowing you to loop through their entries using for...of loops or methods like forEach().
const myMap = new Map([
['name', 'John'],
['age', 30]
]);
for (let [key, value] of myMap) {
console.log(key + ': ' + value);
}
myMap.forEach((value, key) => {
console.log(key + ': ' + value);
});
Maps provide a flexible and efficient way to store key-value pairs and are commonly used for tasks like caching, maintaining order, and implementing data structures like hash tables.