Understanding Map in Javascript - Part 1

js.Srijan

Table of Contents

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();

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");

Map allows keys with different datatype rather than converting them to string. So, in the 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");

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));

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)

Remove all key-value pairs from Map

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

map.clear()

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)

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);

In this article, we learned what is Map and 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.

If you liked this article, please upvote and recommend it to show your support. Feel free to ask any questions in the comments below.

We publish articles on web development and technology frequently. Consider subscribing to our newsletter or follow us on our social channels (twitter, Facebook, LinkedIn).

Share this

Share on social media