JavaScript – Using ES6 Map When Keys Are All Strings

ecmascriptes6javascript

Plain object keys must be strings, whereas a Map can have keys of any type.

But I have little use for this in practice. In nearly all cases, I find myself using strings as keys anyway. And presumably new Map() is slower than {}. So is there any other reason why it might be better to use a Map instead of a plain object?

Best Answer

There are some reasons why I prefer using Maps over plain objects ({}) for storing runtime data (caches, etc):

  1. The .size property lets me know how many entries exist in this Map;
  2. The various utility methods - .clear(), .forEach(), etc;
  3. They provide me iterators by default!

Every other case, like passing function arguments, storing configurations and etc, are all written using plain objects.

Also, remember: Don't try to optimize your code too early. Don't waste your time doing benchmarks of plain object vs Maps unless your project is suffering performance problems.

Related Topic