JS: Map Object

By Xah Lee. Date: . Last updated: .

New in ES2015.

[see JS: the Map Object Tutorial]

Map is the value of the property key "Map" of the global object.

console.log( window["Map"] === Map ); // true

Map is a function.

[see JS: Data Types]

// type of Map
console.log ( typeof Map === "function" ); // true

The parent of Map is Function.prototype. [see JS: Prototype and Inheritance]

// parent of Map
console.log ( Object.getPrototypeOf ( Map ) === Function.prototype ); // true

The purpose of Map is:

  1. To create instance of “map” object. Instance of map object is a collection of key/value pairs as a lookup table data structure. This is different from the generic JavaScript object 〔JS: What's Object? 〕. The map object instance is designed specifically as a lookup table data structure.
  2. Used as a namespace to hold general purpose methods for working with “map” instances.
  3. Holds the property key "prototype". The value of Map.prototype is the parent object of all “map” instances.

Map instances are collections of key/value pairs.

The key can be any JavaScript type.

The value can be any JavaScript type. [see JS: Data Types]

Keys are always distinct.

The insertion order of entries are maintained.

How Map Determines Uniqueness of Keys

The equality test used for determining whether 2 keys in a map is the same as ===, except treatment of NaN (not a number).

NaN === NaN return false, but for map object, NaN is considered same as any NaN.

// this is false
console.log(NaN === NaN); // false

// for map object, NaN is same as any NaN
const m = new Map();
m.set(NaN, "n1");
m.set(NaN, "n2");

console.log(m) // Map { NaN => 'n2' }

Map Constructor

new Map() → creates a empty map.

new Map(iterable) → create a map from values in iterable object iterable.

const m = new Map();

// add new item
m.set(1, "n1");
m.set(2, "n2");

console.log(m) // Map { 1 => 'n1', 2 => 'n2' }
// using nested array as literal expression for map
const m = new Map([ [3, "n3"], [4, "n4"]]);
console.log(m) // Map { 3 => 'n3', 4 => 'n4' }

Any iterable object can be used as argument. [see JS: Iterable]

ECMAScript 2015 §Keyed Collection#sec-map-constructor



JS: Map.prototype


ECMAScript 2015 §Keyed Collection#sec-map-objects

Map Topic

  1. JS: the Map Object Tutorial
  2. JS: Map Object
  3. JS: Map.prototype
  4. JS: Iterate Over Map Object
  5. JS: Convert Object to/from Map
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon