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.
Top comments (0)