Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Collections

The Map object

Reference for the JavaScript Map object: create a key-value collection with any key type, from entries or objects, and how it differs from a plain object.

A Map stores key-value pairs and remembers the order in which keys were first inserted. Unlike a plain object, its keys can be of any type: strings, numbers, objects, functions, even NaN. Keys are never converted to strings, and a map has no inherited keys such as toString to trip over.

You create a map with new Map(), optionally passing an iterable of [key, value] pairs. Arrays of pairs, other maps and the result of Object.entries() all work.

JavaScript
const empty = new Map();
const ages = new Map([["Ada", 36], ["Linus", 28]]);

Try it

JS Creating maps

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Copies, duplicates and key equality

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
new Map()
new Map(iterable)
Name Description
iterable Optional. An iterable whose items are objects (usually two-element arrays) with the key at index 0 and the value at index 1. null and undefined give an empty map.

Return value: a new Map object.

Exceptions: a TypeError if you call Map() without new, if iterable is not iterable, or if one of its items is not an object (for example new Map([1, 2])).

Usage notes

  • Key equality is "same value zero". It is like === except that NaN equals NaN. Two different objects are different keys even when their contents are equal, and +0 and -0 are the same key.
  • Insertion order is the iteration order. Setting an existing key changes its value but not its position. Deleting and re-adding a key moves it to the end.
  • Map or object? Use a Map when keys are not known in advance, are not strings, are added and removed often, or when you need size and reliable order. Use an object for fixed records with known property names and for JSON.
  • Maps do not serialize to JSON. JSON.stringify(new Map([["a", 1]])) gives "{}". Convert first: JSON.stringify([...map]) or Object.fromEntries(map) (string keys only).
  • Copying is shallow. new Map(map) creates a new map but keeps references to the same value objects.
  • Item shape. Only the first two entries of each pair are read. Extra elements are ignored, and a one-element pair gives a value of undefined.
  • Subclassing. class Registry extends Map {} works; the constructor calls the instance's set() for each pair, so an override of set() sees the initial data.
  • Object keys keep objects alive. A Map holds its keys strongly. If entries should disappear when the key object is no longer used elsewhere, use a WeakMap.

Browser support

Map is supported by every current browser and by Node.js.