Map
A collection of key–value pairs where a key can be anything.
Available since: ES2015
Syntax
new Map(entries)Parameters
| Parameter | Type | Description |
|---|---|---|
| entries | Iterable | Optional. An array of [key, value] pairs to start with. |
Return value
MapA new key–value collection.
Examples
Creating and reading:
const ages = new Map([['Anna', 25], ['Oleg', 31]]);
console.log(ages.get('Anna'));
console.log(ages.size);Output:
25
2A key can be an object:
const visits = new Map();
const user = { name: 'Anna' };
visits.set(user, 3);
console.log(visits.get(user));Output:
3Iteration in insertion order:
const ages = new Map([['Anna', 25], ['Oleg', 31]]);
for (const [name, age] of ages) {
console.log(`${name}: ${age}`);
}Output:
Anna: 25
Oleg: 31Notes
Why a Map beats a plain object: keys of any type, the size in size, guaranteed order and no inherited keys like toString. An object is better for a fixed set of fields, a Map for a dictionary that changes often.
JSON.stringify() turns a Map into {}. Convert it first: Object.fromEntries(map).
See also
- Map.prototype.set — Adds or replaces the value for a key.
- Map.prototype.get — Returns the value for a key.
- Set — A collection of unique values.
- Object.fromEntries — Creates an object from a list of key–value pairs.
Related recipes
In the tutorial
- Map and Set — The Map and Set collections in JavaScript: a dictionary with keys of any type and a set of unique values.