Open In App

How to use multiple ternary operators in a single statement in JavaScript ?

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 stretches the code unnecessarily and makes 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.



Example 1: This example explains how we can use 2 ternary operators in a single statement.




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 explains how we can use 2 ternary operators in a single statement.




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
Article Tags :