Increment a Value in an Object using JavaScript

avatar

Borislav Hadzhiev

Tue Nov 09 20212 min read

banner

Photo by Jason An

Increment a Value in an Object #

To increment a value in an object, assign the value of the key to the current value + 1, e.g. obj.num = obj.num +1 || 1. If the property exists on the object, its value gets incremented by 1, and if it doesn't - it gets initialized to 1.

index.js
const obj = { num: 1, }; // โœ… Using dot notation obj.num = obj.num + 1 || 1; console.log(obj.num); // ๐Ÿ‘‰๏ธ 2 // โœ… Using bracket notation obj['num'] = obj['num'] + 1 || 1; console.log(obj.num); // ๐Ÿ‘‰๏ธ 3

To increment a value in an object we can use dot or bracket notation to get the current value associated to the specific property and then use the addition (+) operator to increment the value.

If the specific key in the object contains spaces, hyphens or starts with a special character, use bracket [] notation.

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 object 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 obj = {}; obj.num = obj.num + 1 || 1; console.log(obj.num); // ๐Ÿ‘‰๏ธ 1

Here are some examples of using the logical OR operator:

index.js
console.log(0 || 1); // ๐Ÿ‘‰๏ธ 1 console.log(5 || 1); // ๐Ÿ‘‰๏ธ 5 console.log('test' || 1); // ๐Ÿ‘‰๏ธ "test" 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