Maps vs Objects in ES6, When to use?
Solution 1
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 Map
s 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).
Solution 2
One of the difference between Map
and Object
is:
Map
can use complex data type as its key. like this:
const fn = function() {}
const m = new Map([[document.body, 'stackoverflow'], [fn, 'redis']]);
m.get(document.body) // 'stackoverflow'
m.get(fn) //'redis'
watch out: For complex data type, If you want to get the value, you must pass the same reference as the key.
Object
, it only accept simple data type(number
, string
) as its key.
const a = {};
a[document.body] = 'stackoverflow';
console.log(a) //{[object HTMLBodyElement]: "stackoverflow"}
Solution 3
Object
s are similar to Map
s in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this (and because there were no built-in alternatives), Object
s have been used as Map
s historically; however, there are important differences that make using a Map
preferable in certain cases:
- The keys of an
Object
areString
s andSymbol
s, whereas they can be any value for aMap
, including functions, objects, and any primitive. - The keys in
Map
are ordered while keys added to object are not. Thus, when iterating over it, aMap
object returns keys in order of insertion. - You can get the size of a
Map
easily with thesize
property, while the number of properties in anObject
must be determined manually. - A
Map
is an iterable and can thus be directly iterated, whereas iterating over anObject
requires obtaining its keys in some fashion and iterating over them. - An
Object
has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can be bypassed by usingmap = Object.create(null)
, but this is seldom done. - A
Map
may perform better in scenarios involving frequent addition and removal of key pairs.
Solution 4
This question is a duplicate of but until it's closed, here's my answer from over there:
In addition to the other answers, I've found that Maps are more unwieldy and verbose to operate with than objects.
obj[key] += x
// vs.
map.set(map.get(key) + x)
This is important, because shorter code is faster to read, more directly expressive, and better kept in the programmer's head.
Another aspect: because set() returns the map, not the value, it's impossible to chain assignments.
foo = obj[key] = x; // Does what you expect
foo = map.set(key, x) // foo !== x; foo === map
Debugging maps is also more painful. Below, you can't actually see what keys are in the map. You'd have to write code to do that.
Objects can be evaluated by any IDE:
Armeen Moon
I am a generalist; slowly becoming a specialist in Web Development. I mix art, design, and technology, to create effective experiences that deliver value at scale. My professional goals are simple: surround myself with smart, energetic, creative people while working on solving problems that matter. Specialties: Functional and Object Oriented JavaScript ,Angular+, AngularJS, AWS, CSS/SCSS, Vector/DOM motion graphics, semantic HTML, NodeJS, Golang, and passionate about learning i18n/l10n, a11y, and modern web workflow.
Updated on February 12, 2020Comments
-
Armeen Moon over 4 years
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));
-
Admin almost 8 yearsOr from another point of view: Whenever you need to iterate over your object's properties at the data level (e.g.
for..of
) instead of the program level (e.g.for..in
) use aMap
. More information concerning this terms in this response. -
Bergi about 7 yearsThis doesn't answer the question "What is an applicable example of using Maps over objects?" at all
-
Bergi about 7 yearsPlease don't cross-post your answers. And no, the question is not a duplicate.
-
Carmine Tambascia over 4 yearsI will add as comment also the fact that anytime you don't know what kind of type your key will be and you don't expect string as key data types, then use map stackoverflow.com/questions/32600157/…