When should you use a Map instead of a plain object in JavaScript?
Use a Map when keys are not just strings, when you add and remove entries often, or when you need a reliable size and insertion order. Use a plain object for fixed, string-keyed records.
Explain it simply
A plain object is like a printed form with fixed fields: name, age, city. A Map is like a notebook where you can write anything on the left (a number, an object, even a function) and attach a value on the right.
Differences that matter in interviews:
- Keys: objects turn keys into strings (or symbols); a Map keeps the real key type, so
1and"1"are different. - Size:
map.sizeis direct; an object needsObject.keys(obj).length. - Iteration: Map iterates in insertion order and is directly iterable.
- Inherited keys: a plain object has prototype keys such as
toString, which can cause surprises when you use it as a counter. - Performance: Map is built for frequent additions and deletions.
Example
const counts = new Map();
counts.set(1, "number key");
counts.set("1", "string key");
console.log(counts.size); // 2
console.log(counts.get(1)); // number key
const obj = {};
obj[1] = "a";
obj["1"] = "b";
console.log(Object.keys(obj).length); // 1What to say in the interview
"A Map allows keys of any type, keeps insertion order, has a size property and is designed for frequent inserts and deletes. A plain object coerces keys to strings and inherits prototype properties. For counting or caching arbitrary keys I reach for a Map; for a fixed record I use an object."
Common mistakes
- Using an object as a dictionary for user-supplied keys without guarding against keys like "__proto__".
- Assuming object keys keep their original type.