JavaScript(JS) Map
In JavaScript, a Map is a built-in data structure that allows you to store key-value pairs. It is similar to an object, but with a few key differences.
One of the main differences between a Map and an object is that a Map can use any value as a key, whereas object keys are limited to strings and symbols. Additionally, a Map preserves the order of its entries, whereas object properties are unordered.
Here are some examples of using a Map in JavaScript:
- Creating a
Map:
let myMap = new Map();
This creates a new empty Map instance.
- Adding and retrieving values from a
Map:
let myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
console.log(myMap.get("key1")); // output: "value1"
console.log(myMap.get("key2")); // output: "value2"
In this example, we add two key-value pairs to the Map using the set() method, and then retrieve the values using the get() method.
- Iterating over a
Map:
let myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
for (let [key, value] of myMap) {
console.log(key, value);
}
In this example, we use a for...of loop to iterate over the entries in the Map and log each key-value pair to the console.
- Checking if a
Mapcontains a key:
let myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
console.log(myMap.has("key1")); // output: true
console.log(myMap.has("key3")); // output: false
In this example, we use the has() method to check if the Map contains a key.
