Maps
Map is a collection of key-value pairs, where keys are unique in a map.
Create a new Map
new Map()
creates a new empty map.
let myMap = new Map();
We can also pass an array of key-value pairs, where each pair is an array with key as first element, and value as second element.
let myMap = new Map([
["apple", 20],
["banana", 30],
["cherry", 15]
]);
Add/Set Key-Value
Map.set(key, value)
adds a new entry into the map with the given key
and value
. If the key
if already present, then it sets the given value
for the key
.
let myMap = new Map();
myMap.set("apple", 20);
myMap.set("banana", 30);
for (let [key, value] of myMap) {
console.log(`${key} - ${value}`);
}
Delete Key-Value
Map.delete(key)
removes the entry with the given key
, if present, from the map.
let myMap = new Map([
["apple", 20],
["banana", 30],
["cherry", 15]
]);
myMap.delete("banana");
for (let [key, value] of myMap) {
console.log(`${key} - ${value}`);
}