Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Map.prototype.set: write an entry

The set method adds or updates a key–value pair in a Map and returns that same Map, enabling chaining.

Version: ECMAScript 2015 onward; example target: Node.js 24.22.2

Syntax

map.set(key, value)

map.set(key, value) stores a value under a key without coercion and returns the receiving Map. A new key is appended at the end of insertion order. Updating an existing key replaces its value without changing size or moving the entry; only delete followed by set creates a new position at the end.

Keys use SameValueZero: NaN matches NaN, and -0 is normalized to +0. Object keys and object values are stored as the same references without cloning. Returning the same Map permits map.set(a, 1).set(b, 2).

The receiver must have Map internal data; a plain object, Set, or unhandled Proxy throws TypeError. The method has been standard since ECMAScript 2015. In get-or-create logic, remember that an existing value can be undefined, so get alone does not always test presence.

Examples

const map = new Map();
console.log(map.set("a", 1) === map);
map.set("b", 2).set("a", 3);
console.log(map.size, [...map.keys()].join(","), map.get("a"));
map.delete("a");
map.set("a", 4);
console.log([...map.keys()].join(","));
const key = {};
const value = {};
map.set(key, value);
console.log(map.get(key) === value);
map.set(NaN, 1).set(NaN, 2).set(-0, "zero");
console.log(map.get(NaN), map.get(+0));
try { Map.prototype.set.call({}, "x", 1); } catch (error) { console.log(error instanceof TypeError); }

Result

true
2 a,b 3
b,a
true
2 zero
true

Sources