The Map Object
Map, unlike the object class, does not have extra keys that have to be enumerated. This saves time when iterating over values in the map. The second thing is that a map can have a key of any type where an object’s key must be a string. Lastly, a map has built-in functions for getting values.
The key functions of a map are set, get, has, and delete. “set” adds the key-value pair to the map. “get” retrieves the value of the key. “has” checks if the key exists. Lastly, “delete” removes the key-value pair from the map without error. Each function provides a lot of value to the map class, which is better than spending time coercing an object to do the same job; this makes maps very useful.
These three things make the map extremely useful in situations where key-value pairs need to be stored. The built-in functions add flexibility that a basic object can’t provide. Here’s an example of using a map vs using an object.
So, that’s why to use a map, so what about when?
When To Use Map
A map should be used in select areas of your code. Given the “why”, they should be used when you need to store key-value pairs while the program is running. This is because maps can have keys that can’t be serialized properly in JSON. Furthermore, they would have to be coerced before being serialized. Although it’s not hard, if you only use strings as keys; using more complex keys will be trouble. So, use a map when you need to store key-value pairs that won’t be serialized. With that said, the map object provides a ton of value.