Ternary Operator in JavaScript

The ternary operator in javascript is useful to assign value based on conditions. This operator is used often as a shortcut to the if-else statement. Also, the nested ternary operator is used as a shortcut to if else if statement.

Syntax:
condition ? expressionIfTrue : expressionIfFalse

Example:

var age = prompt(“Please enter your age”);
var isVoter;
age >= 18 ? isVoter = true : isVoter = false;
isVoter ? document.write("You are eligible for voting.") 
        : document.write("You are not eligible for voting.");

Output:

case1: If the user entered age less than 18 then the following message will be printed.

You are not eligible for voting.

case2: If the user entered age greater than or equal to 18 then the following message will be printed.

You are eligible for voting.

**Note:

Possible false expressions are false, null, NaN, 0, the empty string (“”), and undefined.
If the result of the condition is any one of these then the conditional expression will be expressionIfFalse.

Example:

var age = 23;
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log("You can drink ", beverage);

Output:

You can drink Beer.

Nested ternary operators:

The ternary operator is right-associative, which means it can be nested(or chained) in the following way,
It will become similar to if … else if … else if … else

Example using if else if:

var year = prompt("In which year was the javascript appeared?");
if (year > 1995) {
    alert("Wrong: Too late.");
} else if (year < 1995) {
    alert("Wrong: Too early.")
} else {
    alert("Exactly!");
}

Same code can be done with the help of a nested ternary operator.

Example using nested ternary operator:

var year = prompt("In which year was the javascript appeared?");
year > 1995 ? alert("Wrong: Too late.")
            : year < 1995 ? alert("Wrong: Too early.")
            : alert("Exactly!");

Output:

The output of above both examples will be the same as below.

case1: If the user entered 1995 and as it is the correct answer. Alert message will be “Exactly!”.

case2: If the user entered year less than 1995 and as it is the wrong answer. Alert message will be “Wrong: Too early.”.

case3: If the user entered year greater than 1995 and as it is the wrong answer. Alert message will be “Wrong: Too late.”.

Leave a Reply

Your email address will not be published. Required fields are marked *