Problems with Object

  1. Builtin key problem: Many keys already exists in an object through prototypal inheritance.
  2. Problem with iteration: The keys that are inherited may also end up during iteration.
  3. Only string keys
  4. Not optimized for frequent additions.
  5. Passing user defined keys may lead to Object injection attacks.

Maps to the rescue

  1. Clear distinction between user added values and ones that are inherited. User added values can be accesses using Map.prototype.get
  2. Can be iterated using a standard iterator with a for loop.
  3. In maps anything can be the key. Make sure to use WeakMap when using objects as keys because maps will not let it garbage collected and cause memory leaks.
  4. Optimized for frequent additions and iteration.
  5. Provides ergonomics to be used as a hashmap by providing the following methods:
    1. size
    2. clear
    3. iterate
    4. has
  6. Safe to use with user-defined keys.

When should I prefer Map over Object

  1. When the values that goes in are dynamic in nature then use a Map. Stick to Object if there are fixed number of keys with one time use and not much addition.
  2. When the keys needs to be more than string or symbols use Map.
  3. And for all the reasons that are mentioned above.

References