Let's learn about JavaScript Maps.
Maps are similar to objects.
They store the elements in a key/value pair.
However, a map can contain objects, functions, and other data types as a key, unlike objects.
We can create a Map using the new Map() constructor.
To insert it into the map, we use the set() method. We can use objects and functions as keys as well.
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
console.log(map1)
//expected output: Map {"a": 1, "b": 2}
To access the elements, we use the get() method. We call the get method on the key and get the corresponding values.
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
console.log(map1.get('a'));
// expected output: 1
To check if an element is present in the map, we get a function called has()
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
console.log(map1.has('c'))
//expected output: false
Then we have clear() and delete() methods which can enable us to remove data from the map
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
map1.delete('b');
console.log(map1)
//expected output: Map {"a" : 1}
To get the length of the Map we have the property of size which will give us the number of elements present on the map.
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
map1.set('c', 3);
console.log(map1.size);
// expected output: 3
To iterate over the map, we can use for loops or for-each loop. The elements are accessed in the order they have been inserted.
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
map1.set('c', 3);
for (let [key, value] of map1){
console.log(key, "-", value)
}
// a - 1
// b - 2
// c - 3
map1.forEach(function(value, key){
console.log(key + "-" + value)
})
// a-1
// b-2
// c-3
We can iterate over the keys and values individually as well.
for(let values of map1.values()){
console.log(values)
}
//1 2 3
for(let values of map1.keys()){
console.log(values)
}
//a b c
That was a quick overview of the Map object.
Let me know if you have used it in practical application and how did it perform!
Top comments (0)