← All posts
postApril 4, 2026
Map vs Object — When to Use Each
#javascript#map#data-structures

javascript
// Map accepts ANY key type — objects, functions, numbers
const m = new Map();
const keyObj = {};
m.set(keyObj, 'value');
m.set(42, 'the answer');
// Maintains insertion order (Object does too now, mostly)
// Has a reliable .size property
console.log(m.size); // 2
// Iteration is simpler
for (const [key, val] of m) console.log(key, val);
// Object is better for JSON serialization
JSON.stringify(m); // '{}' — Map doesn't serialize!