Unlock the Power of JavaScript Map: Don't Confuse it with Array map!
Raju Saha
Posted on June 26, 2024
When solving problems that can be optimized with caching, many developers use the Map function. However, some developers mistakenly declare a map using a simple empty object or new Map and then set properties directly. While this approach may seem to work, it can lead to confusion during debugging.
Let's look at an example
You might expect the map to contain the entries { 'fruit'=>'Apple', 'vegetable'=>'Tomato' }
, but instead, it remains an empty Map i.e 0, and console only as an object.
This is because the correct way to add key-value pairs to a Map is by using the set method. If you try to interact with the map using has or delete, it will not work as expected:
The correct approach is to use the set and get methods
Let's update the map with a new key-value pair and check the output
As you can see, the set method correctly updates the existing fruit entry. The map now contains two key-value pairs.
To summarize, always use the set and get methods for adding and retrieving properties in a Map. For more information, refer to the MDN documentation.
Posted on June 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.