Maps in Js

Maps in Js

·

2 min read

In JavaScript, the Map object is a collection of key-value pairs, similar to an object, but it has some additional features and benefits. One of the main benefits of using a Map instead of an object is that the keys in a Map can be of any type, not just strings. Additionally, the order of the keys in a Map is maintained.

Here's an example of creating a Map and adding some key-value pairs to it:

const myMap = new Map();
myMap.set('name', 'John');
myMap.set('age', 30);
myMap.set('city', 'New York');
console.log(myMap); // Map { 'name' => 'John', 'age' => 30, 'city' => 'New York' }

The Map object has several useful methods that you can use to work with the key-value pairs, such as:

  • set(key, value): adds a new key-value pair to the Map or updates an existing one.

  • get(key): returns the value associated with the given key.

  • has(key): returns a boolean indicating whether the given key is in the Map.

  • delete(key): removes the key-value pair with the given key from the Map.

  • clear(): removes all key-value pairs from the Map.

  • size: returns the number of key-value pairs in the Map.

Here's an example of using some of these methods:

console.log(myMap.get('name')); // 'John'
console.log(myMap.has('age')); // true
myMap.delete('city');
console.log(myMap.size); // 2

You can also use forEach method, which allows you to iterate over the key-value pairs in a Map:

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

Example 2 :

let mymap = new Map();
mymap.set(1,"ashish");
mymap.set(2,"manish");
mymap.set(3,"satish");
mymap.set(4,"harish");

console.log(mymap);         //map will be printed

for (const value of mymap) {             //key and value both will be printed     
    console.log(value)
}
for (const value of mymap.values()) {             //value will be printed     
    console.log(value)
}
for (const key of mymap.keys()) {             //key will be printed     
    console.log(key)
}

//using forEach
mymap.forEach((value,key)=>{
    console.log(value,key)
})

mymap.delete(2);    //it will delete manish
console.log(mymap)

In conclusion, the Map object is a useful collection type in JavaScript that provides a way to store and work with key-value pairs. It has several useful methods such as set, get, has, delete and clear that can be used to add, retrieve, check and remove key-value pairs from the map. Additionally, it provides a forEach method that allows you to iterate over the key-value pairs in a Map.

Knowing how to use Maps, and the methods it provides can help you write more organized, maintainable and reusable code.