JavaScript Map

The JavaScript Map object is a collection of key/value pairs. It allows you to store, modify, and retrieve data in a structured way. It is a powerful and versatile tool for working with data in JavaScript.

Why should you use it?

  • It makes working with data easier and more efficient.
  • It's easy to use and understand.
  • It provides better performance than other data structures.

Map

The Map object is a simple key/value map. Any value (both objects and primitive values) may be used as either a key or a value.

The Map object is a powerful way to store and retrieve data. It is similar to an Object except that it can store any type of value as a key or value, including objects and functions.

Creating a Map

To create a Map, you can use the new keyword and the Map constructor:

script.js
let myMap = new Map();

Adding and Retrieving Data

Once you have created a Map, you can add data to it using the set() method. The set() method takes two arguments: a key and a value. The key can be any type of value (primitive or object) and the value can be any type of value.

To retrieve a value from a Map, you can use the get() method. The get() method takes one argument: the key for the value that you want to retrieve.

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

console.log(myMap.get('name')); // John
console.log(myMap.get('age')); // 30

Iterating over a Map

You can iterate over a Map using the forEach() method. The forEach() method takes a callback function as an argument. The callback function is called once for each key/value pair in the Map.

script.js
myMap.forEach((value, key) => {
  console.log(key + ' = ' + value);
});
// name = John
// age = 30

Conclusion

The Map object is a powerful way to store and retrieve data. It is similar to an Object except that it can store any type of value as a key or value, including objects and functions. You can use the set(), get(), and forEach() methods to add, retrieve, and iterate over data in a Map.