DEV Community

Mohammad Aziz
Mohammad Aziz

Posted on

JavaScript comparison: Object vs Map

Before we start

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.

Introduction

Objects have been there in JavaScript from it's born. We have used them quite a lot and we will continue to use them like crazy in future. But for now, I wanted to you to be a little curious and ask yourself a question why this new Map has been introduced by the ECMAScript committee? In this post I'll try to answer that when should we use Map instead of Object?

What is a Map object?

According to MDN:

The Map object holds key-value pairs and remembers the original insertion order of the keys.

What's so "special" about the Map?

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 Object?

  • Unlike Object where the key can only be a string, Map object can have the key of any type.
  • The keys in Map are ordered whereas keys in the object are not. This means while iterating over the Map object, we will get the keys in the same order we have added them.
  • Instances of Map object has a key called size and 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).length but 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.
  • A Map object may perform better in scenarios where frequent addition and removal of keys is needed.

When to use Map and when to use Object?

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.

Relevant resources:

Keyed Collections
Maps
Object

Top comments (1)

Collapse
 
iaziz786 profile image
Mohammad Aziz

Thanks, Alekset for your feedback. I have updated the post based on your input.