What is the difference between JS Map and JS Object?
I know that
Map
is hash table implementation for JS, but how does it differ from an object? With regards to how Python dictionaries work, there seems to be no difference.
vs
3 Replies
There's a good explanation on the MDN doc here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#objects_vs._maps
but basically the Map offers a more secure API to manipulate your data than the object does
Map - JavaScript | MDN
The Map object holds key-value pairs and remembers the original insertion
order of the keys. Any value (both objects and
primitive values) may be used as
either a key or a value.
A couple points I think make a difference:
- The key in the Map can be more than string.
- Map is ordered.
Nitpick: An object is also ordered, though it's ordering is not only insertion based but also depends a bit on what the keys are or look like. IIRC symbol keys are always first and in internal insertion order (I think), then come integer-like keys (in numeric order I think), and finally string keys in insertion order. Usually this just boils down to "string keys in insertion order" though.
From a somewhat engine-first standpoint: If you can list all the possible keys in your object, use an object. If you cannot list them or the listing is open-ended (eg. "any elements of form 'foo-' followed by an integer like number), then use a Map. Engines like objects that they can reason about in static terms: A function that always gets objects that have keys A, B and C will be optimized to directly pick out those data fields with an indexed memory access and will not spend time calculating hashes or anything of that sort. Functions that always get objects of random shapes with wildly differing object keys will end up deoptimized to hash based lookup. The objects may still have inidivdual shapes (an internal engine optimisation for objects) but those become more of a hindrance than a benefit. In these cases it is by far preferable to use a proper hash map, which is exactly what Map provides.