InterviewHubPRO
Section Overview
Q501

Question 501 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

96%
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:

FeatureMapObject
Key typesAny typeString/Symbol only
Sizemap.sizeObject.keys(obj).length
IterationDirect iterationRequires conversion
OrderInsertion order guaranteedNot guaranteed (pre-ES2015)
PerformanceBetter for frequent additions/deletionsBetter for simple lookups
PrototypeNo prototype pollution riskHas prototype chain
JSON supportNo direct supportNative 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);