Reputation: 117
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
Reputation: 17103
There is a good explanation on MDN as to when and why prefer Map
over Object
.
To sum it up:
Upvotes: 0
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 :
Map
as an efficient hash table, go for it! That's what it's built for.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