Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Map

A collection of key–value pairs where a key can be anything.

Available since: ES2015

Syntax

new Map(entries)

Parameters

ParameterTypeDescription
entriesIterableOptional. 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
2

A key can be an object:

const visits = new Map();
const user = { name: 'Anna' };
 
visits.set(user, 3);
 
console.log(visits.get(user));

Output:

3

Iteration 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: 31

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.