Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Map.prototype.set

Adds or replaces the value for a key.

Available since: ES2015

Syntax

map.set(key, value)

Parameters

ParameterTypeDescription
keyanyThe key.
valueanyThe 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 2

Counting 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

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.

Thanks for reading!

Donate to the site — we work hard for you.