Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

JavaScript Ternary Operator

  • Difficulty Level : Basic
  • Last Updated : 11 Feb, 2021

Below is the example of the Ternary Operator.

  • Example:
    Program 1:

    Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!




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

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

  • The expression consists of three operands: the condition, value if true and value if false.
  • The evaluation of the condition should result in either 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.

Syntax:



condition ? value if true : value if false
    condition:

  • Expression to be evaluated which returns a boolean value.

    value if true:

  • Value to be executed if condition results in true state.

    value if false:

  • Value to be executed if condition results in false state.

Examples:

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

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

The following programs will illustrate conditional operator more extensively:

Program 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>                  

Output:

Senior Citizen

An example 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> 

Output:

Excellent



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!