In JavaScript, the data structures you use plays an important role in how you organize and manage data in your applications. Occasionally, you might find yourself deciding between using Objects and Maps. Both of these can store and manage data, but there are key differences to consider to know which is the right one for your use case.
Objects have been part of JavaScript since the beginning. and serve as dynamic collections of properties, associating keys with values. Despite their longevity, Objects have some limitations, prompting the emergence of Maps as a more flexible alternative in certain scenarios.
Maps and Objects
Maps can be initialized and used like this:
const map = new Map();
map.set(id, anyData);
map.delete(id);
Objects can be initialized and used like this:
const obj = {};
obj[id] = anyData;
delete obj[id];
As you can see, the two are very similar in their fundamental purpose of storing and managing data in JavaScript. However, there are important differences between them. In the following section, we will explore the key differences between Maps and Objects, shedding light on when and why one may be preferred over the other.
Key Differences
Below I have outlined the five key differences between Object and Maps:
1. Anything as Keys
Developers frequently use different types of keys when dealing with key-value pairs. When using an Object, all keys are automatically converted into strings. This conversion can lead to errors, particularly when it transforms two distinct keys into the same string. In contrast, the Map object provides developers with the flexibility to use keys of any type.
Map
const obj = { 'key': 'value' };
const foo = () => 'value';
const map = new Map([[obj, 'object'], [foo, 'function'], [false, 0]]);
map.keys(); // Object, () => 'value', false
map.get(obj); // 'object'
map.get(foo); // 'function'
map.get(false); // 'boolean'
Object
const obj = { 'key': 'value' };
const foo = () => 'value';
const object = {obj: 'object', foo: 'function', false: 0};
Object.keys(object) // 'obj', 'foo', 'false' - all keys are strings
object[foo] // undefined
object['foo'] // function
2. Iteration
Objects do not support iteration. Yes, of course, there are ways to iterate over objects, but it is less than ideal for real-world uses.
for (const key in object) {
// in result will be the keys that the object inherited
if (object.hasOwnProperty(key)) {
// but it will be a disaster if the hasOwnProperty is overwritten
}
}
But you can improve it a bit and use it like this:
Object.keys(object).forEach(key => {
// do some work here
})
However, the Map is iterable, so we can directly use for...of or forEach with it.
for (const [key, value] of myMap) {
// do some work here
}
Additionally, you can iterate over just keys or values as well:
for (const value of myMap.values()) {
// values are here
}
for (const key of myMap.keys()) {
// keys are here
}
3. Merged with Arrays
Maps seamlessly merge with Arrays. Here is an example:
Map
// Convert Map to Array
const map = new Map([[1, 'foo'], [2, 'bar']]);
const newArr = [...map];
// Convert Array to Map
const newMap = new Map(newArr); { 1 => 'foo', 2 => 'bar' }
// Merge Array and Map
const combinedMap = new Map(...map, newArr);
const combinedArr = [...map, newArr];
Object
const obj = { 1: 'foo', 2: 'bar'};
Array.from(obj) // doesn't work
// this should work
[...Object.entries(obj)] // [ ['1', 'foo'], ['2', 'bar'] ]
4. Ordering
As previously stated, the Map object is iterable, offering the benefit of preserving order during iteration. Traditionally, iterating over a regular object using methods like Object.entries() and Object.keys() didn’t guarantee the retrieval of key-value pairs in their input order. In scenarios where preserving order is crucial, such as algorithmic tasks, the Map object emerges as a better choice.
5. Performance
As a rule, in scenarios where you need to add or delete key-value pairs frequently and in large numbers, Maps performs better. Objects are not optimized for this. Keep in mind, though, that Maps use more memory than Objects because they store additional metadata.
Conclusion
If you require diverse key types and want to avoid potential errors stemming from key conversions, then use the Map object. If you prioritize simplicity and faster reads and writes, stick with Objects. If you want to do iteration, ordering matters, or you need to manipulate arrays, you’ll want to use Map.
Each has its strengths, so choose wisely based on your specific needs and preferences. But the choice is always yours!


