JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to increment a value in an object using JavaScript?

How to increment a value in an object using JavaScript?

To increment a value in an object, access the value of the key, add 1 to it and then assign the incremented value back to the key. On the other hand, if the key does not exist or has an undefined or null value, assign 1 to it.

let obj = {
  num: 5
}

obj.num = obj.num + 1 || 1;
console.log(obj.num); //6

obj['num'] = obj['num'] + 1 || 1;
console.log(obj.num); //7

You access the value assigned to the key using the dot or square notation.

The interesting thing to note here is that the logical OR operator returns the left hand value if the left expression is truthy; otherwise, returns the right hand side value.

let obj = {}

obj.num = obj.num + 1 || 1;
console.log(obj.num); //1

As you can see, the num key does not exist in the object. So, obj.num has an undefined value and when 1 is added to it, it returns NaN. NaN is a falsy value that is why 1 is returned by the logical OR operator.

In JavaScript, the following values are considered falsy: undefined, null, 0 NaN (not a number), "" (empty string), and false. Values other than falsy are truthy values.

Recommended Posts