Initially, when I read about Maps, I had this question running in my mind. Why use Javascript Maps, when objects serve the same purpose?
Unanimous answer found in most of the websites is the reduction of complexity. Let’s dive into this in detail.
In a Nutshell, Maps hold key-value pairs and have below advantages over Objects
- First, we can use different data types like objects, functions and Primitive types as keys which is not possible with objects. Objects can only have strings as keys.
- Second, Maps are iterable. Objects can be iterated by converting to an array or checking if a property belongs to it and not a prototype.
Confusing??? Let’s try iterating through a Javascript object.
Iterating through Javascript Object
a. Use “Object.keys” or “Object.getOwnPropertyNames” with “foreach”
b. Use “for..in” with “hasOwnProperty”
Iterating through Maps in Javascript
It is simple compared to objects. Just use a for loop, that’s it!!!
3. Retrieving size of a map is easy by using “size” property.
Where to use
Let’s see where we can use Javascript Maps. Javascript Maps are useful to store “key-value” pairs. For instance, let’s consider “Two-sum problem”.
Problem Definition
Given an array, return indices of two numbers such that they add up to the given sum
Solution
- Here, we are creating a Map with “Target-number”(difference of current number from required sum) as key and index as value.
- From next index, we check if the “Target-number” exists in the array and return the Array indices if found.
- If not found, we continue with step 1.
Let’s debug the code for given input
i=0 arrayMap[0] does not exist and it adds (7, 0) to arrayMap.
i=1 arrayMap[7] =0 and we will return [0,1] which are the indices.
Javascript Maps – The Tricky Part
We all know about “NaN” in Javascript. It does not have a real value and comparing it to itself doesn’t return true.
Now, here’s a tricky question. Guess the output of code below
let obj= new Map();
obj.set(“Name”,”Test”);
obj.set(NaN,”Test1″);
obj.get(Nan);
If you answer is “Test1”, you are right.
We can use “NaN” as key in Javascript Maps. Appropriate value rendered with “NaN” key.
That’s it, there ends my first post. Hope it was not boring and happy coding!!!