Increment A Value In An Object Using JavaScript

Increment a Value in an Object using JavaScript

Sometimes you need to increment a value in an object. Read this article to learn how to increment a value in an object using JavaScript and avoid unnecessary bugs in the process. Let’s get started.

How to increment a value in an object using JavaScript

We create a simple JavaScript object of key-value pairs.

Example:

// Create the 'obj' object
const obj = {
    key1: undefined,
    key2: 2,
};

console.log(obj);

Output:

{ key1: undefined, key2: 2 }

To increment a value in an object, we first use the '.' or '[]' to access the value of a particular key.

We then increment the value of the key being accessed by 1. However, the output will return NaN when the value of that key is undefined.

Example:

// Create the 'obj' object
const obj = {
    key1: undefined,
    key2: 2,
};

// Increase the value of key1 and key2 by 1
obj.key1 = obj.key1 + 1;
obj["key2"] = obj["key2"] + 1;
console.log(obj);

Output:

{ key1: NaN, key2: 3 }

We will use the conditional (ternary) operator '?:' for our program to work around this error. The conditional (ternary) operator is a shortened version of the if-else statement.

Syntax:

condition ? exprIfTrue : exprIfFalse

Parameters:

condition: an expression used as a condition. Evaluates to FALSE if it is one of the values NaN, null, "", 0, and undefined.

exprIfTrue: an expression to be executed if the condition is TRUE.

exprIfFalse: an expression to be executed if the condition is FALSE.

Example:

// Create the 'obj' object
const obj = {
    key1: undefined,
    key2: 2,
};

// Use the conditional (ternary) operator '?:' to Increment the values in the 'obj' object
obj.key1 ? obj.key1++ : (obj.key1 = 1);
obj.key2 ? obj.key2++ : (obj.key2 = 1);
console.log(obj);

Output:

{ key1: 1, key2: 3 }

If the value of the key entered as a condition is defined, it will be incremented by 1. If the value of the key entered as a condition is undefined, it will be initialized to 1.

You can also use the or operator '||' to increment a value in the obj object.

Example:

// Create the 'obj' object
const obj = {
    key1: undefined,
    key2: 2,
};

// Use the or operator '||' to Increment the values in the 'obj' object
obj.key1 = ++obj.key1 || 1;
obj.key2 = ++obj.key2 || 1;
console.log(obj);

Output:

{ key1: 1, key2: 3 }

Summary

When you increment a value in an object using JavaScript, the program will return NaN if the value is undefined. So you must check if the value is undefined before incrementing a value in an object. Thank you for reading.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *