What are the differences between Map and Object for storing key-value pairs?
Assesses fundamental understanding of JavaScript conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
While both Map and Object store key-value pairs, they have significant differences:
Key types:
// Object - keys are always strings or symbols
const obj = {};
obj[1] = 'one';
console.log(Object.keys(obj)); // ['1'] - converted to string
// Map - keys can be any type
const map = new Map();
map.set(1, 'one');
map.set({}, 'object');
map.set(() => {}, 'function');
Size property:
const map = new Map([['a', 1], ['b', 2]]);
console.log(map.size); // 2
const obj = { a: 1, b: 2 };
console.log(Object.keys(obj).length); // Manual counting
Iteration:
const map = new Map([['a', 1], ['b', 2]]);
// Map is directly iterable
for (const [key, value] of map) {
console.log(key, value);
}
// Object requires Object.entries()
for (const [key, value] of Object.entries(obj)) {
console.log(key, value);
}
Comparison table:
| Feature | Map | Object |
|---------|-----|--------|
| Key types | Any type | String/Symbol only |
| Size | map.size | Object.keys(obj).length |
| Iteration | Direct iteration | Requires conversion |
| Order | Insertion order guaranteed | Not guaranteed (pre-ES2015) |
| Performance | Better for frequent additions/deletions | Better for simple lookups |
| Prototype | No prototype pollution risk | Has prototype chain |
| JSON support | No direct support | Native support |
When to use Map:
// Frequent additions and deletions
const cache = new Map();
cache.set(key1, value1);
cache.delete(key1);
// Non-string keys
const weakMap = new Map();
const domElement = document.getElementById('btn');
weakMap.set(domElement, { clicks: 0 });
When to use Object:
// Simple data structures
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000
};
// JSON serialization needed
const data = { name: 'John', age: 30 };
JSON.stringify(data);
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.