In JavaScript, a Map is a built-in object that allows you to store key-value pairs, similar to an object. However, a Map offers some additional functionality that makes it useful in certain situations.
Here’s an example of creating a Map:
const myMap = new Map();
To add a key-value pair to the Map, you can use the set() method:
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
You can retrieve a value from the Map using the get() method:
console.log(myMap.get('key1')); // output: 'value1'
You can also check if a key exists in the Map using the has() method:
console.log(myMap.has('key1')); // output: true
console.log(myMap.has('key3')); // output: false
To remove a key-value pair from the Map, you can use the delete() method:
myMap.delete('key2');
You can iterate over the keys or values in a Map using a for…of loop:
for (let key of myMap.keys()) {
console.log(key);
}
for (let value of myMap.values()) {
console.log(value);
}
Additionally, you can iterate over both keys and values using the entries() method:
for (let [key, value] of myMap.entries()) {
console.log(key, value);
}
One useful feature of a Map is that you can use objects as keys, rather than just strings or numbers:
const obj1 = {name: 'John'};
const obj2 = {name: 'Jane'};
const myMap = new Map();
myMap.set(obj1, {age: 15});
myMap.set(obj2, {age: 20});
console.log(myMap.get(obj1)); // output: 'value1'
Another advantage of using a Map is that you can easily get the size of the Map using the size property:
console.log(myMap.size); // output: 2
In summary, a Map is a built-in object in JavaScript that allows you to store key-value pairs, with additional functionality for checking key existence, iterating over keys and values, and using objects as keys.
For more information, refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map