What is difference between a map object and a plain object in JavaScript?

JavaScript

Answer ✅

A Map is a specialized data structure for key-value pairs, while a plain Object is a more general-purpose structure. The main difference is that a Map allows keys of any data type and preserves the order of its elements, whereas an Object's keys are limited to strings and symbols and its element order is not guaranteed.

Key Types 🔑

A Map can use any value as a key, including objects, functions, and primitive types. In contrast, an Object coerces all keys into strings (or symbols).

Map Example:

const myMap = new Map();
const myFunction = () => console.log('hello');

myMap.set(myFunction, 'This is a function key!');
myMap.set(123, 'This is a number key!');

console.log(myMap.get(myFunction)); // "This is a function key!"

Object Example:

const myObj = {};
const objKey1 = { a: 1 };
const objKey2 = { b: 2 };

myObj[objKey1] = 'Value 1';
myObj[objKey2] = 'Value 2'; // This overwrites the previous value!

console.log(myObj); // { '[object Object]': 'Value 2' }

Element Order 👉

A Map remembers the original insertion order of its keys. When you iterate over a Map, the elements are returned in the same order they were added. The order of properties in a plain Object is not guaranteed and can be unpredictable.

const myMap = new Map();
myMap.set('c', 3);
myMap.set('a', 1);
myMap.set('b', 2);

for (const [key, value] of myMap) {
console.log(key); // Prints "c", then "a", then "b"
}

Getting the Size 📏

Finding the number of items in a Map is straightforward using the .size property. For an Object, you must manually count the keys, which is less efficient.

  • Map: myMap.size
  • Object: Object.keys(myObj).length

Iteration 🔄

Map objects are directly iterable. You can use a for...of loop to go through their [key, value] pairs without needing extra methods. Objects are not directly iterable; you must use methods like Object.keys(), Object.values(), or Object.entries() to loop over them.

Map Iteration:

for (const [key, value] of myMap) {
// ...
}

Object Iteration:

for (const key of Object.keys(myObj)) {
const value = myObj[key];
// ...
}

Performance 🚀

For scenarios involving frequent additions and removals of key-value pairs, Map generally offers better performance than a plain Object.

Summary Table 📊

FeatureMapObject
Key TypesAny data type (object, function, etc.)Strings and Symbols only
OrderPreserves insertion orderNot guaranteed
SizeDirect via .size propertyManual (Object.keys().length)
IterationDirectly iterable (for...of)Not directly iterable
Default KeysNone. It's a clean slate.Has a prototype with default keys, which can cause conflicts.
Use CaseIdeal for key-value collections and lookup tables.Good for storing and structuring data with string keys.
00:00