Map
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.
Map
Object
Accidental Keys
A Map
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 Types
A Map
's keys can be any value (including functions, objects, or any primitive).
Key Order
The keys in Map
are ordered in a simple, straightforward way: A Map
object iterates entries, keys, and values in the order of entry insertion.
Although the keys of an ordinary Object
are ordered now, this was not always the case, and the order is complex. As a result, it's best not to rely on property order.
The order was first defined for own properties only in ECMAScript 2015; ECMAScript 2020 defines order for inherited properties as well. See the OrdinaryOwnPropertyKeys and EnumerateObjectProperties abstract specification operations. But note that no single mechanism iterates all of an object's properties; the various mechanisms each include different subsets of properties. (for-in
includes only enumerable string-keyed properties; Object.keys
includes only own, enumerable, string-keyed properties; Object.getOwnPropertyNames
includes own, string-keyed properties even if non-enumerable; Object.getOwnPropertySymbols
does the same for just Symbol
-keyed properties, etc.)
Size
The number of items in a Map
is easily retrieved from its size
property.
The number of items in an Object
must be determined manually.
Iteration
A Map
is an iterable, so it can be directly iterated.
Object
does not implement an iteration protocol, and so objects are not directly iterable using the JavaScript for...of statement (by default).
Note:
An object can implement the iteration protocol, or you can get an iterable for an object using
Object.keys
orObject.entries
.The for...in statement allows you to iterate over the enumerable properties of an object.
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.
Examples:
Last updated