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
| Parameter | Type | Default | Description |
|---|---|---|---|
iterable | Iterable | undefined | An 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
sizeproperty 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
| Feature | Map | Object |
|---|---|---|
| Key types | Any | Strings/Symbols |
| Size | .size property | Manual counting |
| Iteration | Iterable by default | Object.keys() needed |
| Order | Guaranteed insertion order | ES2015+ guarantees |
| Default keys | None | __proto__ |
| Performance | Better for frequent changes | Better 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.