Map.prototype.set()
The reason to choose a Map over an object: keys keep their type and their order. A number stays a number, an object works as a key, and nothing is coerced to a string.
Demo
The output is the Map itself, which is what set returns — hence the chainable style. Overwriting an existing key replaces its value but leaves it where it was in the order, so 'a' stays first. The numeric-key case shows the headline difference from a plain object: the keys 1 and 2 remain NUMBERS here, where an object would have converted them to the strings '1' and '2'.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| key | any | yes | Any value at all — string, number, object, function, NaN, symbol. Matched by SameValueZero, so NaN works as a key and 0 and -0 are the same key. |
| value | any | yes | Any value. Setting an existing key overwrites it without changing its position in the insertion order. |
Return value
Map — The SAME Map, so calls chain. It mutates in place — there is no non-mutating variant.
Common patterns
const m = new Map().set("a", 1).set("b", 2);
const m = new Map([["a", 1], ["b", 2]]);
const meta = new Map(); meta.set(domNode, {clicks: 0});
Examples
Pitfalls
const m = new Map(); m.set({id: 1}, "x"); m.get({id: 1})
m.set(1, "x"); m.get(1)
const next = m.set("a", 1); next === m
const next = new Map(m).set("a", 1);
JSON.stringify(new Map([["a", 1]]))
JSON.stringify(Object.fromEntries(new Map([["a", 1]])))
new Map().set(0, "a").set(-0, "b").size
new Map().set("0", "a").set("-0", "b").size
When to use
- Keys that are not strings — numbers, objects, DOM nodes, functions
- Insertion order must be preserved for every key type
- Frequent additions and deletions, where Map is faster than an object
- Keys come from untrusted input, where __proto__ would be a hazard on an object
- String keys you will serialise to JSON → a plain object
- A fixed, known set of fields → an object or a class
- You need spread and destructuring → objects support them directly
- Keys are objects you recreate each time → they will never match
Notes
FAQ
Map when keys are not strings, when insertion order matters for numeric-looking keys, or when keys come from untrusted input. An object when the data is a fixed record you will serialise, spread or destructure — Map supports none of those directly.
new Map([[1, "a"], ["b", 2]]); // key types kept ({1: "a", b: 2}); // keys become strings, reordered