Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Map — a key-value collection

Map stores unique keys of any type together with their associated values. It supports reading and deleting entries, checking whether a key exists, and iterating in insertion order.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

new Map()
new Map(iterable)
map.set(key, value)
map.get(key)
map.has(key)
map.delete(key)
map.clear()
map.size
for (const [key, value] of map) { /* ... */ }

Map is a built-in collection of key-value pairs. Both keys and values can be any JavaScript value. Create an empty map with new Map(), or pass an iterable containing [key, value] pairs to the constructor. Calling it without new throws TypeError.

set(key, value) adds or updates an entry and returns the map. get(key) reads its value; a missing key produces undefined. Because a stored value can also be undefined, check presence with has(key). The size property gives the number of entries, delete(key) returns whether an entry was removed, and clear() removes every entry.

Key comparison follows SameValueZero: NaN matches NaN, and +0 and -0 are the same key. Objects are compared by identity, not by their contents. Two separately created { id: 1 } objects are therefore different keys.

Iteration with for...of yields pairs in key insertion order; keys(), values(), and entries() return the corresponding iterators. Updating a value does not move its entry, but deleting and reinserting moves it to the end. To add entries, use set(key, value), not map[key] = value. Bracket assignment targets an object property, not a map entry. For example, on an unmodified Map instance, map["size"] = value throws a TypeError in strict mode and is ignored otherwise, because the inherited size property has a getter but no setter.

Examples

const key = { id: 1 };
const map = new Map([["first", 1], [key, 2]]);
map.set("first", 3);
map.set(NaN, 4);
map.set(NaN, 5);

console.log(map.size);
console.log(map.get(key));
console.log(map.has({ id: 1 }));
console.log(map.get(NaN));
console.log(JSON.stringify([...map.values()]));

Result

3
2
false
5
[3,2,5]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources