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]'. Mapcompares keys with SameValueZero. This is like===, exceptNaNequalsNaN.- It keeps insertion order.
- It has a
sizeproperty. - You can loop over it directly.
- It has no inherited keys like
constructoror__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
haslookup is fast.array.includesis 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 {}.
Mapkeys can be any type. Plain object keys are only strings or symbols.Maphassize, keeps insertion order, can be looped over, and has no prototype key collisions.- Use
Setfor unique values and fast membership checks. - Plain objects are better for records and for JSON.
JSON.stringifydoes not save the contents of aMaporSet.
Read more
- Map and Set (https://javascript.info/map-set)javascript.info
- Map (MDN) (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)developer.mozilla.org