Map.prototype.set
Adds or replaces the value for a key.
Available since: ES2015
Syntax
map.set(key, value)Parameters
| Parameter | Type | Description |
|---|---|---|
| key | any | The key. |
| value | any | The value. |
Return value
MapThe same Map — so calls can be chained.
Examples
Adding and replacing:
const stock = new Map();
stock.set('apples', 10).set('pears', 4);
stock.set('apples', 7);
console.log(stock.get('apples'), stock.size);Output:
7 2Counting words:
const counts = new Map();
for (const word of ['a', 'b', 'a', 'c', 'a']) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(Object.fromEntries(counts));Output:
{
"a": 3,
"b": 1,
"c": 1
}Notes
Keys are compared like ===: the string '1' and the number 1 are different keys, and so are two different objects even if they look the same.
See also
- Map.prototype.get — Returns the value for a key.
- Map.prototype.has — Checks whether a key is in a Map.
- Map.prototype.delete — Removes the entry for a key.
In the tutorial
- Map and Set — The Map and Set collections in JavaScript: a dictionary with keys of any type and a set of unique values.