DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Understanding Map in Javascript - Part 1
Srijan
Srijan

Posted on • Originally published at hackinbits.com

Understanding Map in Javascript - Part 1

This article was first published on hackinbits.com


What is Map

Map is a collection of key and value pairs, similar to Object. The main difference between a Map and an Object is that Map allows key on any type either primitive or an object.

Let’s learn how to create a Map and do operations on it.

Creating a Map

You can create a Map by using the new keyword

let map = new Map();
Enter fullscreen mode Exit fullscreen mode

This will create an empty Map.

Add a new element to Map

To set a key with the value we use map.set(key, value)

map.set("1", "my key is a string");
map.set(1, "my key is a Number");
map.set(true, "my key is a boolean");
Enter fullscreen mode Exit fullscreen mode

Map allows keys with different datatype rather than converting them to string. So, in above example, "1" and 1 are two distinct keys.

We can also use objects as keys in Map.

let myObj = {name: "John Doe"};
map.set(myObj, "my value");
Enter fullscreen mode Exit fullscreen mode

Access an element in a Map

To get the value, we use map.get(key) method.

//output: "my key is a string"
console.log(map.get("1"));

//output: my key is a Number
console.log(map.get(1));
Enter fullscreen mode Exit fullscreen mode

We should not access Map using object syntax: map[key]. This will make Map behave similar to a javascript object with all the limitations of an object.

Remove a key-value pair in Map

To delete a key-value pair from a Map we use map.delete(key).

map.delete(true)
Enter fullscreen mode Exit fullscreen mode

Remove all key-value pairs from Map

To remove all key-value pairs from Map we use map.clear()

map.clear()
Enter fullscreen mode Exit fullscreen mode

Count number of elements in a Map

To count the number of elements in Map we use map.size

let map = new Map();
map.set(1, "one");
map.set(2, "two");

//output: 2
console.log(map.size)
Enter fullscreen mode Exit fullscreen mode

Check if a key exists in a Map

To check if a key-value pair exists in Map we use map.has(key)

//output: true
map.has (1);
Enter fullscreen mode Exit fullscreen mode

In this article, we learned basic operations that we can perform on Map. In the next article, we will learn how to iterate over Map and convert it to array and object and vice versa.

Top comments (0)

git push

Stop by this week's meme thread!