Sunday, May 19, 2024
197
rated 0 times [  200] [ 3]  / answers: 1 / hits: 27871  / 9 Years ago, wed, september 16, 2015, 12:00:00

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

More From » ecmascript-6

 Answers
45

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


[#65053] Sunday, September 13, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryonk

Total Points: 161
Total Questions: 116
Total Answers: 107

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
bryonk questions
;