When should we choose map over object literal?

The map is a collection of key-value pairs like Objects.

But the main difference is map allows keys of any type(primitive/non-primitive).

When we try to store an object as a key in Object, it converts all keys to strings and the resulted value would be stored as a key in Object, which means if we try to store 1 as a key we could able to access with 1(Number) and ‘1’ (String) see the following code for better understanding.

object_as_key.png

number_as_key.png

Definitely, this is not what we want. It breaks the code when we choose an object as a key.

It’s one of the reasons to choose a map over an Object.

Choose map over an object in following scenario’s

  • keys are unknown until run time.

  • Map Preservers the order of storing keys, while iteration prints the same order in which it was inserted.

  • Object compares keys by using the strict equality check(===) whereas map follows the SameValueZero algorithm (it’s pretty much similar to === but the difference is that NaN is equal to NaN)

Methods and properties are:

new Map() — creates the map.

map.set(key, value) — stores the value by the key.

map.get(key) — returns the value by the key, undefined if the key doesn’t exist in

map.has(key) — returns true if the key exists, false otherwise.

map.delete(key) — removes the value by the key.

map.clear() — removes everything from the map.

map.size — returns the count of props.

Map.set call returns map indeed so we can use

map.set(‘1’, ‘str1’)
.set(1, ‘num1’)
.set(true, ‘bool1’);

Iterations

map.keys() — returns an iterable for keys, map.values() — returns an iterable for values, map.entries() — returns an iterable for entries [key, value]

// iterate over keys
for (let key of map.keys()) {
console.log(key);
}

// iterate over values
for (let value of map.values()) {
console.log(value);
}

// iterate over [key, value] entries
for (let entry of map) {
console.log(entry);
}