JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)
What are the differences between Map and Object for storing key-value pairs?
While both Map and Object store key-value pairs, they have significant differences:
Key types:
javascript
// 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:
javascript
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:
javascript
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:
javascript
// 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:
javascript
// Simple data structures
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000
};
// JSON serialization needed
const data = { name: 'John', age: 30 };
JSON.stringify(data);