Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 545
Armeen Harwood Avatar asked Oct 06 '22 04:10

Armeen Harwood


People also ask

Should I use Map or object JS?

An object behaves like a dictionary because JavaScript is dynamically typed, allowing you to add or remove properties at any time. But Map() is much better because it: Provides get , set , has , and delete methods. Accepts any type for the keys instead of just strings.

What are the advantages of using ES6 maps over objects?

Prior to the introduction of Maps in ES6, objects were generally used to hold key-value pairs. Maps have advantages over objects when creating hash maps because: You can use different data types (i.e., primitives, objects, functions) as keys. You can easily get the size of a map through it's size property.

Why should we stop using objects as maps in JavaScript?

This is because the in operator designates properties in the object's prototype as being part of the object, which we don't really want for dictionaries or maps. To create a pure object with no prototype, we have to write: let obj = Object. create(null);


1 Answers

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

like image 55
Bergi Avatar answered Oct 24 '22 23:10

Bergi