Increment a Value in an Object using JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 9, 2021

banner

Photo from Unsplash

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 #

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.