Skip to content
UniCircle
MediumConceptualObjects

Map and Set vs plain objects

Question JS-OBJ-002

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] and obj['1'] are the same key).
  • You add and delete keys often: Map is optimised for that.
  • You need the size: map.size, versus Object.keys(obj).length.
  • Keys come from users: a plain object has inherited keys like constructor or __proto__ that can clash; a Map has none.
JavaScript
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 order

Plain objects remain best for fixed, known shapes (records, JSON) because they serialise directly with JSON.stringify.

Original UniCircle question. Last reviewed 22 Oct 2026.