Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any disadvantage of using Map over Object in Javascript?

Are there any noticeable benefits of using Object over ES6's Map()? I like using it for the forEach function. Is it a bad practice to opt for Map() when needing hash tables?

like image 609
Anthony Avatar asked Mar 23 '18 08:03

Anthony


People also ask

Is map better than object JavaScript?

An object behaves like a dictionary because JavaScript is dynamically typed, allowing you to add or remove properties at any time. But Map() is much better because it: Provides get , set , has , and delete methods. Accepts any type for the keys instead of just strings.

When would you use maps over objects?

Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type. Use objects when there is logic that operates on individual elements.

What are the advantages of using ES6 map over objects?

Prior to the introduction of Maps in ES6, objects were generally used to hold key-value pairs. Maps have advantages over objects when creating hash maps because: You can use different data types (i.e., primitives, objects, functions) as keys. You can easily get the size of a map through it's size property.

What is a benefit of using a map instead of a plain JavaScript object to store key-value pairs?

The map accepts any key type As presented above, if the object's key is not a string or symbol, JavaScript implicitly transforms it into a string. Contrary, the map accepts keys of any type: strings, numbers, boolean, symbols. Moreover, the map preserves the key type. That's the map's main benefit.


1 Answers

The case of Object vs Map in the context of Javascript is more of a question of whether you want a generic or specialized tool for the job.

Map is actually just a special kind of object (just like any other type of object that you would construct in your application. You could even make your own Map() constructor function to mimic ES6 Maps). Like other objects, it has methods to access its functionalities. The "specialty" of the Map is to be an efficient key-value store.

The Object on the other hand is one of Javascripts native data types, and can be used for a variety of purposes (Map being one of them). It is not "specialized" for any one purpose.

So, in conclusion :

  • If you are using a Map as an efficient hash table, go for it! That's what it's built for.
  • If you are using Map for anything other than a key value store (or, as you say, just because of the forEach method) you may have to reconsider using it in favour of a more suitable data structure (which may or may not be a plain old object)
like image 162
Soham Kamani Avatar answered Oct 21 '22 01:10

Soham Kamani