Saturday, July 18, 2020

Objects vs. Maps


source: MDN documentation

Object is similar to Map—both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), Objects have been used as Maps historically.
However, there are important differences that make Map preferable in certain cases:
MapObject
Accidental KeysMap does not contain any keys by default. It only contains what is explicitly put into it.
An Object has a prototype, so it contains default keys that could collide with your own keys if you're not careful.
Note: As of ES5, this can be bypassed by using Object.create(null), but this is seldom done.
Key TypesMap's keys can be any value (including functions, objects, or any primitive).The keys of an Object must be either a String or a Symbol.
Key Order
The keys in Map are ordered. Thus, when iterating over it, a Map object returns keys in order of insertion.
The keys of an Object are not ordered.
Note: Since ECMAScript 2015, objects do preserve creation order for string and Symbol keys. In JavaScript engines that comply with the ECMAScript 2015 spec, iterating over an object with only string keys will yield the keys in order of insertion.
SizeThe number of items in a Map is easily retrieved from its size property.The number of items in an Object must be determined manually.
IterationMap is an iterable, so it can be directly iterated.Iterating over an Object requires obtaining its keys in some fashion and iterating over them.
Performance
Performs better in scenarios involving frequent additions and removals of key-value pairs.
Not optimized for frequent additions and removals of key-value pairs.

No comments:

Post a Comment

function declaration, expression and call/invoke/execution

  The  function  declaration defines a function with the specified parameters. The  function   keyword can be used to define a function ins...