What is the difference between Map and object?
Both store key–value pairs, but Map is purpose-built for collections.
Keys — Map allows any type (objects, functions); object keys are strings or symbols.
Order — Map preserves insertion order.
Size & iteration — Map has .size and is directly iterable; objects need Object.keys.
Performance — Map is optimised for frequent additions and deletions.
Use a Map for dynamic key–value data; a plain object for fixed, structured records.
// Object — string keys only
const obj = { name: 'John', age: 30 };
console.log(Object.keys(obj).length); // 2 (verbose)
// Map — any key type
const map = new Map();
const objKey = { id: 1 };
map.set(objKey, 'User 1'); // Object as key!
map.set(42, 'The answer'); // Number as key!
map.set(true, 'Yes'); // Boolean as key!
console.log(map.get(objKey)); // 'User 1'
console.log(map.size); // 3 (direct property)
console.log(map.has(42)); // true
// Iteration
for (const [key, value] of map) {
console.log(key, value); // Maintains insertion order
}
// Map from object and back
const map2 = new Map(Object.entries(obj)); // Object → Map
const obj2 = Object.fromEntries(map2); // Map → ObjectMap supports any key type (objects, numbers, booleans). .size is a direct property (no Object.keys needed). for...of works directly on Map. Object.entries/fromEntries convert between Map and Object.
Map is better for dynamic collections; objects for static records.
Map: any key type, .size, iterable, better for dynamic data. Object: simpler syntax, JSON compatible, better for records.
Know the conversion: Object.entries → Map, Object.fromEntries → Object. Map does not have prototype pollution risk.