Borislav Hadzhiev
Tue Nov 09 2021·2 min read
Photo by Jason An
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
.
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.
[]
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).
1
.const obj = {}; obj.num = obj.num + 1 || 1; console.log(obj.num); // 👉️ 1
Here are some examples of using the logical OR operator:
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
.