Open In App

JavaScript Ternary Operator

Last Updated : 07 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The JavaScript Ternary Operator, also known as the Conditional Operator, offers a better approach to expressing conditional (if-else) statements. It operates on three operands: a condition, a value to return if the condition is true, and a value to return if the condition is false. This article is a comprehensive guide to understanding and using the Ternary Operator effectively in JavaScript.

Examples

Input: let result = (10 > 0) ? true : false;
Output: true
Input: let message = (20 > 15) ? "Yes" : "No";
Output: Yes

Syntax

condition ? trueExpression : falseExpression

Operands

  • condition: Expression to be evaluated which returns a boolean value.
  • value if true: Value to be executed if the condition results in a true state.
  • value if false: Value to be executed if the condition results in a false state.

Characteristics of Ternary Operator

  • The expression consists of three operands: the condition, value if true, and value if false.
  • The evaluation of the condition should result in either a true/false or a boolean value.
  • The true value lies between “?” & “:” and is executed if the condition returns true. Similarly, the false value lies after “:” and is executed if the condition returns false.

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

Javascript
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.

Javascript
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. 

Javascript
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

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads