JS: the Map Object Tutorial

By Xah Lee. Date: . Last updated: .

New in ES2015.

  1. Map objects are collections of key/value pairs. Each pair is called a “entry”.
  2. The key can be any value type. [see JS: Value Types]
  3. The value can be any value type.
  4. Keys are always distinct.
  5. The insertion order of entries are maintained.

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?

Creating Map

new Map() → creates a empty map.

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

[see JS: 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 JS: Map Constructor]

[see JS: Convert Object to/from Map]

Parent of Map Objects

The parent of any map object is Map.prototype.

[see JS: Prototype and Inheritance]

[see JS: Map.prototype]

Size of Map

map_obj.size → returns the total count of entries in map_obj.

[see JS: Map.prototype.size]

Set/Add a Entry

map_obj.set(key, val) → add an entry to the map. If the key already exists, overwrite its value. Returns the modified map.

[see JS: Map.prototype.set]

Delete a Entry

map_obj.delete(key) → delete the entry of key. Returns true if found, else false.

[see JS: Map.prototype.delete]

Check Existence

map_obj.has(key) → return true if key exist. Else, false.

[see JS: Map.prototype.has]

Get Value of a Key

map_obj.get(key) → return the value of the key key. If key isn't found, return undefined.

[see JS: Map.prototype.get]

Clear Map

JS: Map.prototype.clear

Iterate Map

JS: Iterate Over Map Object

Get All Keys

JS: Map.prototype.keys

Get All Values

JS: Map.prototype.values

Add Arbitrary Properties to Map

Because map is a object, you can still add arbitrary properties to a map object. (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' ]

JS Map

  1. the Map Object Tutorial
  2. Iterate Over Map Object
  3. Convert Object to/from Map
  4. Map Filter
  5. Reverse Key/Value

Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog