Anthony
Anthony

Reputation: 117

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?

Upvotes: 8

Views: 1987

Answers (2)

Daniel Macak
Daniel Macak

Reputation: 17103

There is a good explanation on MDN as to when and why prefer Map over Object.

To sum it up:

  • Map has useful properties, utility functions and is Iterable, which saves you some writing compared to using Object (like while trying to find number of key-value pairs)
  • Map can be more performant in intensive key-value operations (adition, removal)
  • Map prevents unwanted collisions between your keys and predefined Object's prototype properties
  • Map can use objects for keys

Upvotes: 0

Soham Kamani
Soham Kamani

Reputation: 552

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)

Upvotes: 5

Related Questions