DEV Community

Raju Saha
Raju Saha

Posted on

Unlock the Power of JavaScript Map: Don't Confuse it with Array map!

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
map setting properties just like object
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:
checking it by map methods
The correct approach is to use the set and get methods
correct Approcah of map
Let's update the map with a new key-value pair and check the output
Updating the properties
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.

Top comments (0)