Map data structure in JavaScript
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
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.
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.
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.
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.
Thanks for reading :)
Reference: Map