Borislav Hadzhiev
Last updated: Nov 10, 2021
Check out my new book
To increment a value in a Map
, use the set()
method on the Map, passing it
the name of the key and the value as parameters, e.g.
map.set('num', map.get('num') + 1 || 1);
. If the key exists in the Map
, the
value gets incremented, and if it doesn't, it gets initialized to 1
.
const map1 = new Map([['num', 1]]); console.log(map1.get('num')); // 👉️ 1 map1.set('num', map1.get('num') + 1 || 1); console.log(map1.get('num')); // 👉️ 2
To increment a value in a Map, we passed the following 2 parameters to the Map.set() method:
key
in the Mapvalue
We used the
Map.get()
method to get the value that corresponds to the key, so we can increment it by
1
.
We used the logical OR (||) operator, which returns the value to the left if it's truthy, otherwise it returns the value to the right.
Truthy are all values that are not falsy.
The falsy values in JavaScript are: false
, null
, undefined
, 0
, ""
(empty string), NaN
(not a number).
Map
or it contains a falsy value, the logical OR (||) operator will return the value to the right, effectively setting the value of the key to 1
.const map1 = new Map(); console.log(map1.get('num')); // 👉️ undefined map1.set('num', map1.get('num') + 1 || 1); console.log(map1.get('num')); // 👉️ 1
Here are some examples of using the logical OR operator:
console.log(0 || 1); // 👉️ 1 console.log(100 || 1); // 👉️ 100 console.log('str' || 1); // 👉️ "str" console.log(undefined || 1); // 👉️ 1 console.log(null || 1); // 👉️ 1 console.log(NaN || 1); // 👉️ 1
The only scenario where the operator returns the value to the left is if it's
truthy, e.g. a number other than 0
.