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.
const empty = new Map(); const ages = new Map([["Ada", 36], ["Linus", 28]]);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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 thatNaNequalsNaN. Two different objects are different keys even when their contents are equal, and+0and-0are 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
Mapwhen keys are not known in advance, are not strings, are added and removed often, or when you needsizeand 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])orObject.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'sset()for each pair, so an override ofset()sees the initial data. - Object keys keep objects alive. A
Mapholds 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.