Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 08 Mar, 2021

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, 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 the condition2. If condition2 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:



Javascript




<script>
  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 bellow 30");
</script>;

Output:

You are between 30 and 69

Example 2:

Javascript




<script>
  const num = 12; num != 0 ? num > 0 ? 
  console.log("Entered number is positive") : 
  console.log("Entered number is negative") : 
  console.log("You entered zero");
</script>

Output:

Entered number is positive
My Personal Notes arrow_drop_up
Recommended Articles
Page :