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:
Adds a new key-value pair to the Map.
const myMap = new Map();
myMap.set('name', 'John');
myMap.set('age', 30);
Retrieves the value associated with the specified key.
console.log(myMap.get('name')); // Output: John
Returns true if the Map contains the specified key, otherwise false.
console.log(myMap.has('name')); // Output: true
Removes the key-value pair associated with the specified key. Returns true if the key existed in the Map, otherwise false.
myMap.delete('name');
Removes all key-value pairs from the Map.
myMap.clear();
Returns the number of key-value pairs in the Map.
console.log(myMap.size); // Output: 0
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);
}
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);
}
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);
}
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.