A detailed guide to the use of JavaScript ternary operators

The following is an example of a ternary operator.

Example:

Procedure 1:

<script>  
     function gfg() {  
     //Javascript to illustrate 
     //Conditional operator 
  
     let PMarks = 40 
     let result = (PMarks > 39)? 
         "Pass" : "Fail" ; 
  
     document.write(result); 
     }  
     gfg();  
</script>

The output is as follows:

Pass

A “question mark” or “conditional” operator is a ternary operator in JavaScript that has three operands.

  • An expression consists of three operands: conditional, value if true, and value if false.
  • The condition should be evaluated to true/false or a boolean value.
  • The value of true is between ?” & “: “, and is executed if the condition returns true. Similarly, the false value is after “:”, and if the condition returns false, the false value is executed.

The syntax is as follows:

condition ? value if true : value if false

Condition:

To evaluate the expression, it returns a boolean value.

If true:

The value to be executed when the condition is true.

If false:

If the condition results in an error state, the value that will be executed.

Example:

Input: let result = (10 > 0) ? true : false;
Output: true

Input: let message = (20 > 15) ? "Yes" : "No";
Output: Yes

The following procedures illustrate conditional operators more broadly:

Procedure 1:

<script>  
     function gfg() {  
     //JavaScript to illustrate 
     //Conditional operator 
  
     let age = 60 
     let result = (age > 59)? 
         "Senior Citizen" : "Not a Senior Citizen" ; 
  
     document.write(result); 
     }  
     gfg();  
</script>

The output is as follows:

Senior Citizen

Examples of multiple conditional operators.

Program 2:

<script>  
     function gfg() {  
     //JavaScript to illustrate
     //multiple Conditional operators
  
     let marks = 95;
     let result = (marks < 40) ? "Unsatisfactory" : 
              (marks < 60) ? "Average" :
              (marks < 80) ? "Good" : "Excellent" ;
  
     document.write(result);
     }  
     gfg();  
</script>

The output is as follows:

Excellent