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?
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.
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.
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.
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.
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)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With