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:| 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. |
| Key Types | A Map'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. |
| 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. | 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