Increment a Value in a Map using JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 10, 2021

banner

Photo from Unsplash

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.