How to use multiple ternary operators in a single statement in JavaScript ?
In JavaScript, the ternary operator (? :) is a shorthand for if-else statements. You can use multiple ternary operators in a single statement to handle multiple conditions efficiently. This makes your code shorter, but be cautious as too many nested ternary operators can reduce code readability.
Syntax:
condition1 ?(condition2 ? Expression1 : Expression2) : Expression3;
In the above syntax, we have tested 2 conditions in a single statement using the ternary operator. In the syntax, if condition1 is incorrect then Expression3 will be executed else if condition1 is correct then the output depends on condition2. If condition 2 is correct, then the output is Expression1. If it is incorrect, then the output is Expression2.
Example 1: Using Multiple Ternary Operators
In this example, we are checking two conditions and using nested ternary operators to return the corresponding expression based on the conditions:
const age = 45;
(age > 30) ? (age > 70) ?
console.log("You are getting old") :
console.log("You are between 30 and 69") :
console.log("You are below 30");
Output
You are between 30 and 69
Example 2: Another Example with Multiple Conditions
Let's look at another example where we use multiple ternary operators to determine a grade based on a score:
const num = 12;
(num != 0) ? (num > 0) ?
console.log("Entered number is positive") :
console.log("Entered number is negative") :
console.log("You entered zero");
Output
Entered number is positive
Using multiple ternary operators in a single statement can simplify your code when handling multiple conditions. However, it is essential to balance code conciseness with readability to avoid making the logic too complex.