Difference Between

Object and Map

Before Map was introduced, Object has been used as map for a long time in Javascript world. Although both providing some similar functionalities such as storing data as key-value pair, add/delete/check existence of key/value, they have some differences:

Key Differences

Accidental Keys

  • Map: is an empty container by default. It only contains what is explicitly put into it.
  • Object: has a protytype, so it contains default keys in the prototype chain, you might accidentially override some default keys if not careful.

Security

  • Map: is safe to use with user-provided keys and values.
  • Object: using user-provided key-value might allow attackers to override the object's prototype, lead to object injection attack. We could prevent this issue with null prototype object.

Key Types

  • Map: key can be any values (functions, objects, primitives, etc).
  • Object: key must be a string or a symbol.

Key Order

  • Map: ordered by the insertion order.
  • Object: more complex, it's suggested not to rely on the object's properties order.

Size

  • Map: easy to retrieve from the size property.
  • Object: not direct, but can achieve through the length of array returned from Object.keys.

Iteration

  • Map: is iterable, so it can be directly iterated.
  • Object: does not implement iteration protocol, so objects are not directly iterable using the for...of statement. You can do so through Object.keys or Object.entries or for...in.

Performance

  • Map: better in scenario involving frequent addition and removal of key-value pairs.
  • Object: not optimized for frequent addition and removal of key-value pairs.

Serialization and parsing

  • Map: Not natively support.
  • Object: Native support for serialization (JSON.stringify) and parsing (JSON.parse).

Readmore

Last Update: 04:52 - 18 April 2024

On this page