Open In App

JavaScript Ternary Operator

JavaScript Ternary Operator (Conditional Operator) is a concise way to write a conditional (if-else) statement. Ternary Operator takes three operands i.e. condition, true value and false value. In this article, we are going to learn about Ternary Operator.

Examples

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

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

Syntax

condition ? trueExpression : falseExpression

Operands

Characteristics of Ternary Operator

Example 1: Below is an example of the Ternary Operator.






function gfg() {
    // JavaScript to illustrate 
    // Conditional operator 
    let PMarks = 40
    let result = (PMarks > 39) ?
        "Pass" : "Fail";
  
    console.log(result);
}
gfg();

Output
Pass

 



Example 2: Below is an example of the Ternary Operator.




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

Output
Senior Citizen

Example 3: Below is an example of nested ternary operators. 




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

Output
Excellent

Article Tags :