Javascript Map vs Object — What and when?

JavascriptFront End TechnologyObject Oriented Programming

According to MDN Docs,

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

The important thing to note here is that objects can also be used as keys in maps. This is not the case with JavaScript objects. JS objects only allow primitives to be used as keys.

Another feature that makes it useful in certain scenarios is that it is iterable. And it is iterable in order of insertion. So in cases where you need to maintain the order of keys as well as have a value associated with it, the map can be used.

Example

Example usage of maps −

const myMap = new Map();
const keyString = 'a string',
const keyObj = {},
const keyFunc = function() {};
// setting the values with all kinds of keys
myMap.set(keyString, "String Val");
myMap.set(keyObj, 'Object val');
myMap.set(keyFunc, 'function val');
console.log(myMap.size);
console.log(myMap.get(keyString));

Output

This will give the output −

3
String Val
raja
Published on 02-Dec-2019 06:28:19
Advertisements