JavaScript: Map Object Tutorial

By Xah Lee. Date: . Last updated: .

New in JS2015.

The map object is designed to be used as a map data structure (similar to Python Dictionary or Ruby Hash Table or Java Map. ).

What's the difference between object and map?

Create Map

new Map()
Create a empty map.
new Map(iterable)
Create a map from values in iterable object iterable.

[see Iterable]

const m = new Map();

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

console.log(m) // Map { 1 => 'n1', 2 => 'n2' }

There's no literal expression for map. But you can pass in a literal expression of array of array, like this:

new Map([ [key1, val1], [key2, val2] …])

const m = new Map([ [3, "n3"], [4, "n4"]]);

console.log(m) // Map { 3 => 'n3', 4 => 'n4' }

Note: the map constructor (new Map()) does not accept a object datatype.

[see Map Constructor]

[see Convert Object to/from Map]

Parent of Map Objects

The parent of any map object is Map.prototype.

[see Prototype and Inheritance]

[see Map.prototype]

Size of Map

map_obj.size

[see Map.prototype.size]

Set/Add a Entry

map_obj.set(key, val)

[see Map.prototype.set]

Delete a Entry

map_obj.delete(key)

[see Map.prototype.delete]

Check Existence

map_obj.has(key)

[see Map.prototype.has]

Get Value of a Key

map_obj.get(key)

[see Map.prototype.get]

Clear Map

Map.prototype.clear

Iterate Map

Iterate Over Map Object

Get All Keys

Map.prototype.keys

Get All Values

Map.prototype.values

Nested Map

 const nestedMap = new Map([
    ["tall",
     new Map([
         ["old", new Map([["John",59751],["Mary",68534]])],
         ["young", new Map([["Joe",37235],["Smith",34426]])]
     ])
    ],
    ["short",
     new Map([
         ["old", new Map([["Jane",22328],["Connie",28459]])],
         ["young", new Map([["Jenny",67962],["David",69887]])]
     ])
    ]]);

console.log( nestedMap.get("tall").get("old").get("Mary") ); // 68534

Add Arbitrary Properties to Map

Because map is a object, you can add object properties to it, but you shouldn't do it.

const m = new Map([[3, "n3"], [4, "n4"], [5, "n5"] ]);

// you can add arbitrary properties to a map object
m.pp = 22;
console.log(m.pp) // 22

console.log(Object.getOwnPropertyNames(m)); // [ 'pp' ]

JavaScript Map Object

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc