CodePark/ questions / Arrays & objects
START PRACTICINGPRACTICE
Frontend question · JavaScript › Arrays & objects

When would you use a Map or Set instead of a plain object or array?

Use a Map when keys are not strings, or when you add and remove keys often. Use a Set when you need unique values or fast "is it in here?" checks.

Map:

  • Keys can be any value, including objects and functions. Plain object keys are always strings or symbols, so obj[{}] turns the key into '[object Object]'.
  • Map compares keys with SameValueZero. This is like ===, except NaN equals NaN.
  • It keeps insertion order.
  • It has a size property.
  • You can loop over it directly.
  • It has no inherited keys like constructor or __proto__ that could collide with your keys.
  • It is optimized for frequent additions and deletions.

Set:

  • It stores unique values.
  • It is the standard way to remove duplicates: [...new Set(arr)].
  • Its has lookup is fast. array.includes is linear, which means it checks items one by one.

Plain objects are still better for fixed-shape records, like a user with id and name. They are also better for anything you need to serialize: JSON.stringify turns a Map or Set into {}.

  • Map keys can be any type. Plain object keys are only strings or symbols.
  • Map has size, keeps insertion order, can be looped over, and has no prototype key collisions.
  • Use Set for unique values and fast membership checks.
  • Plain objects are better for records and for JSON.
  • JSON.stringify does not save the contents of a Map or Set.