Maps vs Objects in ES6, When to use?

What is an applicable example of using Maps over objects?

I think you’ve given one good example already: You at least need to use Maps when you are using objects (including Function objects) as keys.

in particular, “when would keys be unknown until runtime?”

Whenever they are not known at compile time. In short, you should always use a Map when you need a key-value collection. A good indicator that you need a collection is when you add and remove values dynamically from the collection, and especially when you don’t know those values beforehand (e.g. they’re read from a database, input by the user, etc).

In contrast, you should be using objects when you know which and how many properties the object has while writing the code – when their shape is static. As @Felix has put it: when you need a record. A good indicator for needing that is when the fields have different types, and when you never need to use bracket notation (or expect a limited set of property names in it).

Leave a Comment