In this article, we will see how we can use multiple ternary operators in a single statement in JavaScript. Sometimes using conditional statements like if, else, and else if stretch the code unnecessarily and make the code even more lengthy. One trick to avoid them can be the use of ternary operators. But what if we are to use multiple if-else statements? Such issues can be tackled using multiple ternary operators in a single statement.
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.
In the above syntax, we can see how we can use more than one ternary operator in a single statement. Below is an example explaining how we can use 2 ternary operators in a single statement.
Example 1: This example shows the use of the ternary operator in JavaScript.
Javascript
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: This example shows the use of the ternary operator in JavaScript.
Javascript
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