JavaScript : Map Methods

JavaScript Maps come with a variety of methods that provide functionality for working with the key-value pairs they contain. Here's an overview of some common methods available for Maps:

1. set(key, value)


Adds a new key-value pair to the Map.


const myMap = new Map();

myMap.set('name', 'John');
myMap.set('age', 30);

 

2. get(key)


Retrieves the value associated with the specified key.


console.log(myMap.get('name')); // Output: John
 

3. has(key)


Returns true if the Map contains the specified key, otherwise false.


console.log(myMap.has('name')); // Output: true
 

4. delete(key)


Removes the key-value pair associated with the specified key. Returns true if the key existed in the Map, otherwise false.


myMap.delete('name');
 

5. clear()


Removes all key-value pairs from the Map.


myMap.clear();
 

6. size


Returns the number of key-value pairs in the Map.


console.log(myMap.size); // Output: 0
 

7. keys()


Returns a new iterator object that contains the keys for each element in the Map, in insertion order.


const keysIterator = myMap.keys();
for (let key of keysIterator) {
  console.log(key);
}

 

8. values()


Returns a new iterator object that contains the values for each element in the Map, in insertion order.


const valuesIterator = myMap.values();
for (let value of valuesIterator) {
  console.log(value);
}

 

9. entries()


Returns a new iterator object that contains an array of [key, value] pairs for each element in the Map, in insertion order.


const entriesIterator = myMap.entries();
for (let [key, value] of entriesIterator) {
  console.log(key + ': ' + value);
}

 

10. forEach(callbackFn)


Executes a provided function once for each key-value pair in the Map, in insertion order.


myMap.forEach((value, key) => {
  console.log(key + ': ' + value);
});

 

These methods provide powerful capabilities for working with JavaScript Maps, allowing you to manipulate, retrieve, and iterate over key-value pairs efficiently.