What is the Map object in JavaScript?

Map

A Map is a collection of key—value pairs similar to an object. It stores the key-value pairs in the insertion order.

Methods available in Map methods:

  • set(key, value) — sets the value for the key in the Map and Returns the Map. If the key is already present in the map, the value is overwritten.

  • get(key) — returns the value associated with the key; or, it returns undefined if there is no key on the Map that matches the passed key.

  • delete(key) — deletes the entry that matches the passed key and returns true if the key is deleted. If the key is not found on the map, it returns false.

  • clear() — deletes all key-value pairs from the Map.

  • has(key) — returns true if the map has the key provided; else, it returns false.

  • keys() — Returns a new Iterator that contains the keys in insertion order.

  • values() — Returns a new Iterator that contains the values in insertion order.

  • entries() — Returns an Iterator that has an array of key-value pair in insertion order.

Properties available in Map

  • size — Returns the current Map size (total number of entries).
console.log("Map in JavaScript");
let map = new Map();
console.log("\n---------\nAdding Values")
map.set('happy', "😃");
map.set("sad", "😔");
map.set("angry", "😡");
console.log(`Elements in map`, map);
console.log("\n-------\nAdding duplicate key to map");
map.set('sad', '☹️'); // new property is overwritten
console.log(`Elements in map after adding duplicate entry with different value`, map);
console.log("\n-------\nGetting value from map");
console.log(`Getting value for key happy ${map.get('happy')}`); // 😃
console.log(`Getting value for key angry ${map.get('angry')}`); // undefined
console.log("\n-------\nhas method");
console.log(`\nChecking if happy is present in map ${map.has('happy')}` ); // true
console.log(`\nChecking if smile is present in map ${map.has('smile')}` ); // false
console.log("\n--------\nSize of map = ", map.size); // 3
console.log("\n--------\nGetting keys of map");
console.log(...map.keys());
console.log("\n--------\nGetting values of map");
console.log(...map.values());
console.log("\n--------\nGetting entries of map");
console.log(...map.entries());
console.log("\n-------\ndeleting keys")
console.log(`Deleting 'happy' ${map.delete('happy')}`); // true
console.log(`Deleting 'smile' ${map.delete('smile')}`); // true
console.log(`After deleting map is `, map);
console.log("\n-------\nClearing the map");
map.clear();
console.log(`After clearing map is`, map);

Things you should know about Map

Use Any type as key

You can use any value (object or function or primitive ) as a key in the Map. The Map uses the SameValueZero algorithm. This algorithm is similar to strict equality (===), except that NaN is considered equal to NaN (i.e,NaN === NaN → true). Normally, this is not true; however, here, NaN is equal to NaN, so the duplicate NaN is avoided.

var map = new Map()
var obj = {};
var arr = [];
var nan = NaN;
var fun = function() {}
map.set(obj, "object");
map.set(arr , "array");
map.set(fun, "function");
map.set(nan, "Wrong number");
console.log("Keys =>", ...map.keys()) ;

Iterating through Map

Using for…of


// we can create a map from array of entries of key-value pair
var map = new Map( [ [ 'happy', '😃' ], [ 'sad', '😔' ], [ 'angry', '😡' ]] );
for(var [key, val] of fruits) {
    console.log(key, val);
}

Why do we need Map if we have Object?

  • A Map is similar to an Objectkeys are only Strings and Symbols , except that any value can be used as a key in maps.

  • We can get the size of the Map, but we don’t have a built-in method to get the size of the Object (though we can do it manually).

  • Maps are iterable; whereas, an object is not iterable by default.

  • Maps have additional methods that are not available to normal objects.

Free Resources

Attributions:
  1. undefined by undefined