What are Map and Set? When would you use a Map instead of a plain object?
Show the explanation
Model answer.
- A `Set` stores unique values of any type, in insertion order. Typical use: removing duplicates (
[...new Set(ids)]) or fast membership checks (seen.has(x)). - A `Map` stores key–value pairs where keys can be any type (objects, functions, numbers), in insertion order.
Prefer Map over a plain object when:
- Keys are not strings (an object coerces keys to strings:
obj[1]andobj['1']are the same key). - You add and delete keys often:
Mapis optimised for that. - You need the size:
map.size, versusObject.keys(obj).length. - Keys come from users: a plain object has inherited keys like
constructoror__proto__that can clash; aMaphas none.
const visits = new Map();
visits.set(userObj, 3); // object as a key
visits.get(userObj); // 3
for (const [k, v] of visits) {} // iterates in insertion orderPlain objects remain best for fixed, known shapes (records, JSON) because they serialise directly with JSON.stringify.
Original UniCircle question. Last reviewed 22 Oct 2026.
