Increment a Value in a Map using JavaScript

avatar

Borislav Hadzhiev

Wed Nov 10 20212 min read

Increment a Value in a Map using JavaScript #

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.

index.js
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:

  1. The name of the key in the Map
  2. The name of the value

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).

If the key does not exist in the 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.
index.js
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:

index.js
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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee