JavaScript · The language round
When should you use a Map instead of a plain object?
Short answer
Map accepts keys of any type, preserves insertion order, exposes size, and is designed for frequent additions and deletions. Plain objects are better for JSON-shaped records and property access.
Objects and Maps both store key-value pairs, but they optimise for different use cases. A Map is a purpose-built collection; an object is a language primitive with a prototype.
const counts = new Map();
counts.set("js", 3);
counts.set("css", 2);
counts.set(42, "answer");
console.log(counts.get("js")); // 3
console.log(counts.has(42)); // true
console.log(counts.size); // 3
for (const [key, value] of counts) {
console.log(key, value);
}Key differences
- Map keys can be objects, functions or any primitive; object keys are strings or symbols
- Map preserves insertion order for iteration
- Map has a
sizeproperty; object size needsObject.keys(obj).length - Map is not serialized by
JSON.stringifyby default - Object literals inherit from
Object.prototype, which can collide with keys such astoString
Use a Map when the key is not a string, when you need frequent add/delete operations, or when you need a reliable iteration order. Use an object when the data is a record with a known shape or must be serialized to JSON.
const cache = new Map();
function memoize(fn) {
return (key) => {
if (!cache.has(key)) cache.set(key, fn(key));
return cache.get(key);
};
}WeakMap is a separate structure with object-only keys and weak references. Use it when you do not want the cache to keep keys alive.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What types can be used as Map keys?
- 2Why is `map.size` simpler than counting object keys?
- 3How do you convert a Map to an array?
- 4Why is a Map not serialized like an object?
Say it in the interview
A Map is a dedicated key-value collection. It accepts any key type, preserves insertion order, has a size property, and is efficient for frequent additions and deletions. A plain object is better for fixed-shape records and JSON. I use Map for caches and indexes where keys are not strings, and objects for data that needs to be serialized.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.