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.
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.
To create a Map
, you can use the new
keyword and the Map
constructor:
let myMap = new Map();
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.
myMap.set('name', 'John');
myMap.set('age', 30);
console.log(myMap.get('name')); // John
console.log(myMap.get('age')); // 30
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
.
myMap.forEach((value, key) => {
console.log(key + ' = ' + value);
});
// name = John
// age = 30
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
.