Javascript: Usage of Map
In Javascript, you can use Map to store key-value pairs. The map allows to store any data types for Key not just strings or symbols. Here’s a basic usage of how to use map.
// Creating a new Map
let myMap = new Map();
// Adding key-value pairs to the Map
myMap.set('key1', 'value1');
myMap.set(2, 'value2');
myMap.set(true, 'value3');
// Getting values from the Map
console.log(myMap.get('key1')); // Output: value1
console.log(myMap.get(2)); // Output: value2
console.log(myMap.get(true)); // Output: value3
// Checking if a key exists in the Map
console.log(myMap.has('key1')); // Output: true
// Deleting a key-value pair from the Map
myMap.delete(2);
// Iterating over the Map
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
// Getting the size of the Map
console.log(myMap.size); // Output: 2 (after deleting one entry)
In addition to the basic usage, Map
has various methods for manipulating and iterating its entries. It also preserves the order of the inserted elements, making it useful in scenarios where the order of insertion matters.
Here’s a simple example of using an array of arrays to initialize a Map
:
let myMapFromArray = new Map([
['key1', 'value1'],
[2, 'value2'],
[true, 'value3']
]);
This initializes the myMapFromArray
with the same key-value pairs as the previous example.