What is the use of map object in javascript?

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, a map can be used.


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


This will give the output −

String Val
Updated on 02-Dec-2019 06:27:20