Member-only story

When Should You Use a Map Instead of an Object in JavaScript?

When to Use Map vs Object in JavaScript

Max N
3 min readFeb 27, 2024
Photo by Patrick on Unsplash

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');

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet