Map

new Map()
Returns: Map · Updated March 13, 2026 · Map and Set
map collection key-value es6

The Map object holds key-value pairs and remembers the original insertion order of its keys. Unlike plain JavaScript objects, Map keys can be of any type—strings, numbers, objects, or even NaN.

Syntax

new Map()
new Map(iterable)

Parameters

ParameterTypeDefaultDescription
iterableIterableundefinedAn array or other iterable whose elements are key-value pairs (e.g., [[key1, value1], [key2, value2]])

Examples

Creating and populating a Map

const userRoles = new Map();

userRoles.set('alice', 'admin');
userRoles.set('bob', 'editor');
userRoles.set('charlie', 'viewer');

console.log(userRoles.get('alice'));
// admin

console.log(userRoles.has('bob'));
// true

console.log(userRoles.size);
// 3

Initializing with an iterable

const config = new Map([
  ['theme', 'dark'],
  ['language', 'en'],
  ['notifications', true]
]);

for (const [key, value] of config) {
  console.log(`${key}: ${value}`);
}
// theme: dark
// language: en
// notifications: true

Using objects as keys

const cache = new Map();

const obj = { id: 1 };
cache.set(obj, 'cached value');

console.log(cache.get(obj));
// cached value

Common Patterns

Converting from an object

const obj = { a: 1, b: 2, c: 3 };
const map = new Map(Object.entries(obj));

console.log(map.get('a'));
// 1

Converting to an object

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const obj = Object.fromEntries(map);

console.log(obj);
// { a: 1, b: 2, c: 3 }

Counting occurrences

const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const counts = new Map();

for (const fruit of fruits) {
  counts.set(fruit, (counts.get(fruit) || 0) + 1);
}

console.log(counts);
// Map(3) { 'apple' => 3, 'banana' => 2, 'orange' => 1 }

When to Use Map

Use Map when you need:

  • Keys that are not strings (objects, numbers, etc.)
  • A guaranteed insertion order
  • A size property for easy counting
  • Frequent additions and deletions
  • Iteration in a predictable sequence

Use a plain object when:

  • Keys are only strings or symbols
  • You need JSON serialization
  • The data is relatively static
  • You want prototype inheritance

Map vs Object

FeatureMapObject
Key typesAnyStrings/Symbols
Size.size propertyManual counting
IterationIterable by defaultObject.keys() needed
OrderGuaranteed insertion orderES2015+ guarantees
Default keysNone__proto__
PerformanceBetter for frequent changesBetter for static data

Browser and Node.js Support

Map is supported in all modern browsers and Node.js 0.12+. For older environments, use a polyfill or fallback to a plain object with a custom implementation.

See Also