JavaScript : Maps

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:

Creating a Map:


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']
]);

 

Adding and Retrieving Elements:


Maps provide methods to add and retrieve elements:

  • set(key, value): Adds a new key-value pair to the Map.
  • get(key): Retrieves the value associated with the specified key.

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

 

Checking for Existence and Size:


You can check if a key exists in a Map and get its size:

  • has(key): Returns true if the Map contains the specified key, otherwise false.
  • size: Returns the number of key-value pairs in the Map.


const myMap = new Map();

myMap.set('name', 'John');
console.log(myMap.has('name')); // Output: true
console.log(myMap.size);        // Output: 1

 

Deleting and Clearing:


Maps provide methods to delete specific key-value pairs or clear all entries:

  • delete(key): Removes the key-value pair associated with the specified key.
  • clear(): Removes all key-value pairs from the Map.

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

 

Iterating Over Maps:


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.