DEV Community

Cover image for Reasons to prefer Map over Object in JavaScript
Rahul
Rahul

Posted on

Reasons to prefer Map over Object in JavaScript

A map is one of the most frequently used data structures. It keeps key-value pairs that can easily be accessed by their keys.

const map = {}; 
map['key1'] = 'value1'; 
map['key2'] = 'value2'; 
map['key3'] = 'value3'; 

// check if map contains key
if (map['key1']) {
    console.log('Map contains key'); 
}

// get value with specific key
console.log(['key1']); 
Enter fullscreen mode Exit fullscreen mode

Reasons to prefer map over the object in JavaScript

More key types

An object can only have symbols or strings. A map can have any type of value as a key: objects, functions, or primitives.

Direct iteration

An object must be iterated by getting the keys and iterating over them.
A map can be iterated directly.

for (let [key, value] of map) {}
 // Map Iteration

for (let key of Object.keys(plainObjMap)) {
    const value = plainObjMap[key]; 
} // Object Iteration
Enter fullscreen mode Exit fullscreen mode

Key order

Object keys are not guaranteed to be in a specific order before ECMAScript 2015.
Map guarantees that keys appear in the order of insertion.

No key overriding

The object already contains some keys on creation because of its prototype. The map does not contain any keys on creation.

const map - new Map(); 
map.set('toString', 2); // No problem for Map

const plainObjMap = new Map(); 
plainObjMap['toString'] = 3; // Error
Enter fullscreen mode Exit fullscreen mode

Note: Since ECMAScript 2015, Accidental key overriding can be avoided by using Object.create(null) to create an object.

Better size determination

Object size has to be determined in a hard way and it takes 0(n) steps.
The map can provide size property and it takes0(1) time.

Better performances

Maps are optimized for frequent addition and removal of entries. Moreover, the number of entries of a Map can be retrieved in constant time.
It is not necessary to convert any key into a string, which can save a lot of time.


😎 Thanks For Reading | Happy Coding ⚡

Top comments (0)