JavaScript Map and Set

Map and Set key equality, including NaN, +0 and -0, and object identity, compared with ordinary objects and arrays.

模块页正文目前为英文。

Map and Set are ECMAScript built-ins. A Map holds key/value pairs. A Set holds unique values. Neither is a DOM collection, and neither is the same as a plain object or an array.

Keys and values are compared with SameValueZero: NaN equals NaN, and +0 equals -0. Object keys are compared by identity, not by their contents.

Examples were checked in Node.js 22, which implements these ECMAScript built-ins. See the MDN documentation for the complete API.

JavaScript tutorial and API overview →

API index

APISummary
Map.prototype.set and getStore and retrieve a value by key using SameValueZero equality.
Set.prototype.add and hasAdd a unique value and test membership.

Map key equality

map.set(NaN, value) can be read back with map.get(NaN). Setting -0 after +0 overwrites the same entry; the two zeros are not separate keys.

When the key is an object, get() looks up that same object reference. A new object with the same properties is a different key.

Map.prototype.set and get

map.set(key, value)
map.get(key)
map.has(key)

Store and retrieve a value by key using SameValueZero equality.

Returns: set() returns the map. get() returns the value, or undefined when the key is missing. has() returns a boolean.

  • undefined is a valid stored value, so has() is the reliable missing-key test.
  • Map iteration order is insertion order, including for numeric keys. That differs from Object.keys().
javascript
const map = new Map();
map.set(NaN, "nan");
console.log(map.get(NaN), map.has(NaN), map.size);
map.set(0, "zero");
map.set(-0, "neg");
console.log(map.get(0), map.get(-0), map.size);
const key = { x: 1 };
const byObject = new Map([[key, "a"]]);
console.log(byObject.get(key), byObject.get({ x: 1 }));

Expected output

nan true 1
neg neg 2
a undefined

Related: Object keys

MDN documentation →

Set uniqueness

A Set stores unique values with the same equality rules as Map. The number 1 and the string "1" are different values. NaN is added only once.

Set.prototype.add and has

set.add(value)
set.has(value)

Add a unique value and test membership.

Returns: add() returns the set. has() returns a boolean.

  • Use a Set when you need membership or uniqueness. Use an array when you need duplicates or index positions.
javascript
const unique = new Set([1, 1, NaN, NaN, "1"]);
console.log([...unique].map((value) => typeof value + ":" + String(value)).join(","));
console.log(unique.has(NaN), unique.has("1"), unique.has(1));

Expected output

number:1,number:NaN,string:1
true true true

MDN documentation →