Member-only story
Objects and Maps in JavaScript seem very similar at first glance. They both allow you to store key-value pairs and access the values by their keys. However, there are some key differences that make Maps better suited for certain use cases. So when should you use a Map instead of a plain Object in JavaScript?
The Main Differences
Maps were introduced in ES6 to address some of the limitations of using plain Objects as maps. Here are the main differences:
- Map keys can be any data type
- Objects have prototype members
- Map keys are ordered
- Map sizes are easily calculated
- Objects can only have string or symbol keys
Let’s explore those key differences in more detail…
Map Keys Can Be Any Data Type
With plain Objects, the keys must be either strings or symbols. But Maps allow keys of any data type:
const map = new Map();
map.set('string key', 'value');
map.set(1, 'number key');
map.set(true, 'boolean key');
map.set({obj: true}, 'object key');