As you might have guessed from the quality of this post, this is my first technical blog post. As I always wanted to write more but haven't had the courage to be vulnerable and put my work in front of a developer like you. Now, I'm being little less fearful and little more valiant to start my journey of becoming a writer, please forgive me for my mistakes; I know there are many.
Map has been introduced by the ECMAScript committee? In this post I'll try to answer that when should we use
Map instead of
According to MDN:
Mapobject holds key-value pairs and remembers the original insertion order of the keys.
There are quite a few special things about the
Map objects but I'll talk only which are relevant to this post, more importantly, how they are different from
Objectwhere the key can only be a string,
Mapobject can have the key of any type.
- The keys in
Mapare ordered whereas keys in the object are not. This means while iterating over the
Mapobject, we will get the keys in the same order we have added them.
- Instances of
Mapobject has a key called
sizeand as the name suggest, it gives us the size of the map object. You can do that for objects too by doing
Object.keys(object).lengthbut that looks like an ad hoc solution.
- Since map objects are iterable, iterating over them is quite easy whereas to iterate over the properties of an object we have to first get all the keys and iterate on the key to get the value associated to that key.
Mapobject may perform better in scenarios where frequent addition and removal of keys is needed.
Quoting the points from the MDN docs on Keyed Collections:
- Use maps over objects when keys are unknown until runtime, and when all keys are the same type and all values are the same type.
- Use maps if there is a need to store primitive values as keys because object treats each key as a string whether it's a number value, boolean value or any other primitive value.
- Use objects when there is logic that operates on individual elements.
Thank you very much for reading my first try on a technical blog. One of the ways I can grow is through your feedback so, please take your valuable time to share your thought with discussion form.