Matthew Harwood Matthew Harwood - 4 months ago 11
Javascript Question

Maps vs Objects in ES6, When to use?

Ref: MDN Maps


Use maps over objects when keys are unknown until run time, and when
all keys are the same type and all values are the same type.

Use objects when there is logic that operates on individual elements.


Question:



What is an applicable example of using Maps over objects? in particular, "when would keys be unknown until runtime?"

var myMap = new Map();

var keyObj = {},
keyFunc = function () { return 'hey'},
keyString = "a string";

// setting the values
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

console.log(myMap.get(keyFunc));

Answer

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).