Interview Q&A / Data Structures & Algorithms

BeginnerQuick answer1 min readUpdated 3 Oct 2026

When should you use a Map instead of a plain object in JavaScript?

SHORT ANSWER

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 1 and "1" are different.
  • Size: map.size is direct; an object needs Object.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

js
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); // 1

What 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.

#hashing#javascript

Related questions

Practise more Data Structures & Algorithms questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Data Structures & Algorithms quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.