Map data structure in JavaScript

Asifur Rahman
2 min readMay 6, 2021

--

In this article, i am going to go over everything in Map and how it is different from Object and also better in some cases

What is Map?

Map is a JavaScript data structure. You can add, edit, delete, check and iterate over Map just like Object, but there are some exceptions.

How to create Map?

Let’s create a Map.

let map = new Map();

and that’s it. You created a Map. But the Map is empty so let’s add some value

setting value to map example

with set(key,value) method you can set a new value to a Map. The first parameter is the key and the second parameter is the value. Also, you can check the size of the Map with the size property.

Note: A Map's keys can be any value (including functions, objects, or any primitive). Yes you have independency in choosing the Map key which we cannot do in Object.

You can check if a key is in the Map or not by has() method. It takes one parameter which is the specific key you want to check and it will return a boolean value.

Map has example

Now that we can add values to a Map, we should also be able to delete those values. And you can do that with the delete() method. This method accepts one parameter and that is the specific key you want to delete and it will return a boolean value indicating the deletion is successful or not.

example of deleting value

The iteration on Map is also very straightforward. You can use forEach method which we used in Array. Also, you can use for-of loop for iteration.

iteration on Map example

Additional features of Map are that you can add an object as a Map key and also convert a 2D Array into a map and vice versa.

image from -> developer.mozilla.org

Thanks for reading :)

Reference: Map

--

--

Asifur Rahman
Asifur Rahman

Written by Asifur Rahman

0 Followers

learner, knowledge seeker

No responses yet