JavaScript Map vs Object

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
84754
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
84754
4.8
Start Learning
Topics Covered

Is It Better to Use Map or Object in JavaScript?

In JavaScript, we frequently have to deal with the use of key-value pairs. For this purpose, Use of an object is the most fundamental strategy. Objects are handy in Javascript, they allow us to combine various types of data.

After ES6, the language gained a new feature called Map. It appears to be a more capable Object with a fairly awkward interface in many ways. But most users still use objects when they want to store key-value pairs and only transition to using Map when they discover that their use cases require more complex keys than simple strings.

Map had long been underutilised in the JavaScript community because of this inertia.

So, who wins the race between javascript map vs object? In this article, we will discuss when and how to use Map over Object in Javascript, and vice versa.

Difference between Javascript Map vs Object

Map is a data structure, storing data in the form of key-value pairs, which contains a unique key and value mapped to the key. Furthermore, no duplicate pair is retained due to the uniqueness of each key that is kept.

The Javascript Map is created as:

An object in Javascript is also a data structure following the key-value structure, with each key being unique, better called as a ‘property’. However, they are still quite different from Maps in many aspects, which we will discuss now. A javascript object can be created as:

The fundamental differences between Javascript Map vs Object are:

(These differences are the reasons why a new data structure Map was developed in ES6 and the limitations Object had.)

  1. In Object, the data type of the key can only be a string or symbols. Other types will automatically be converted to strings. On the other hand, Map takes any type of key.

For example,

The keys declared in the above creation of objects are integers (4 and 7). But at the time of accessing them, they are automatically converted to strings.

Handling code with this implicit conversion of data types is a challenge because the consistency of the data types is lost.

  1. Map preserves the original order of elements with respect to the insertion. However, this is not the case with objects. Sometimes when the order of insertion is important, Map will be preferred over objects. This ordering in iteration is achieved by the so-called deterministic hash tables algorithm used by Javascript. Note that Maps are internally implemented using hash tables.

  2. Objects are not iterable directly. To perform an iteration over the objects, we need to use Object.keys() or Object.values() to obtain the list of keys, values or the pairs. Similar is the case for the purpose of finding the length of the object, use the above methods and find the length of the returned array by .length. In short, it can be said that there are no proper helper methods for objects. On the other hand, a simple method .size() returns the size of the map.

  3. Prior to ES6, a hash map could only be created by creating an empty object. However, this hashMap object is still not empty after creation, this is because every object inherits traits from its prototype object. Because of this, even though we never explicitly specified methods like hasOwnProperty, toString, constructor on hashMap on the object, we may use them on hashMap.

Because of this inheritance, there can be name collisions. A name collision happens when a method is created with the same name as in the parent (parent’s method is overwritten)

For example,

In addition, any change to Object.prototype at runtime will have an impact on all objects due to the way JavaScript's property resolution mechanism operates. This makes big JavaScript applications vulnerable to prototype pollution attacks, which can pose a severe security risk.

  1. Map is an instance of an Object, but vice versa isn’t true.

Hence, the above code will output true when Map is checked for being an instance of Object, and false for checking if Object is an instance of Map.

Some More Differences:

Here we discuss some more differences between Javascript Map vs Object specific to how they are declared, access etc.

1) Declaration

Object: There are many ways to create an object.

By using direct literal

By using constructor

By using Object.prototype.create

Map: Unlike Object, there is only one way to create a Map, using the new keyword. Arrays in javascript can also be created in a similar way. This is because they are an instance of Object, and an Object in javascript can be created this way.

2) Accessing Element Object: We can use the dot operator or the bracket notations. (Object. and Object[‘key’])

Map: We use Map.prototype.get(key)

Retrieving a value for a particular key doesn’t require to scan through the whole data and can be done in O(1) for both Map as well as Object. This is because they internally use hash tables which offer a nearly constant time complexity because of their structure.

3) Check if a key already exists Map: Using the has() method

Object: Using the ‘===’ operator to compare with undefined

Another way,

In Object, Object.prototype.hasOwnProperty() can be used in case we want to only check a key which is not inherited for that object.

4) Adding new Element Map: Using Map.prototype.set() method. It will add a new element to the map with the specified key-value pair, and if the key is already present it will overwrite the previous value corresponding to that key. Because map preserves the order of insertio, the new element will appear in the last while iterating.

Object

5) Getting the size Map: For map, it’s quite simple, map.size provides the size of the map

Object: For Object, there’s not a direct way, first we find the array of keys or values or the pairs using Object.keys() or Object.values() and then find the size of the array using .length.

When And Where To Use Object Given all these differences, Map seems to be a much better choice to use for storing key-value pairs. However, Map is not here to replace Object. Even with all of Map's benefits over objects, there are still situations when objects perform more effectively. After all, the most fundamental idea in Javascript is the Object.

  • Objects could be a better option if we just use string-based keys and need the fastest read speed. This is because Javascript engines convert objects down to C++ classes in the background and the access path for properties is significantly faster than a function call for Map().get(), and. The form of the class changes when a property is added or removed, which requires the supporting class to be recompiled and makes utilising an object as a dictionary with numerous additions and removals quite sluggish. However, reading existing keys without modifying the object is very quick.
  • In situations when it is necessary to apply distinct logic to certain properties or elements, objects are unquestionably the best option.

For example (can’t be done with a Map),

  • JSON has direct support for Object, but not with Map. So objects are preferred where there are a lot of tasks involving JSON.
  • Again, Map is purely hash and Object is much more than that.

Conclusion

In this article, we discussed all the possible differences between Javascript Map vs Object, including the different ways of declaration, accessing elements etc as well as issues in Object that led to the introduction of Map in ES6. To conclude, we reiterate through the important points, as follows:

  • In order to choose between Map and Object, it truly relies on the type of data (input) you'll be working with and the operations you'll run on it.
  • In situations when we only require a straightforward look-up structure for data storage, with all the fundamental actions it supplied, Map tends to have greater advantages than Object. Maps have advantages like being iterators and having simple size look-ups.
  • Despite the fact that map offers several benefits over object, map cannot completely replace object in JavaScript since object is more than just a hash table. And also hence if there is an alternative option (Map), it shouldn't be utilised just for hashing.