JavaScript - Conditional or Ternary operator (?:)
The JavaScript conditional or ternary operator returns one of the two values based on the value of boolean expression. It is kind of similar to the if-else statement and helps to write the if-else statements in a short way.
Syntax
//returns value1 if expression is true //returns value2 if expression is false expression ? value1 : value2
Return Value
Returns value1 if the expression is evaluated to be true, and value2 if the expression is evaluated to be false.
Example:
In the example below, the ternary operator is used to find out the maximum of two numbers.
var x = 50; var y = 100; var txt; //maximum of two value var max = (x > y) ? x : y; txt = "Maximum value = " + max;
The output (value of txt) after running above script will be:
Maximum value = 100
Example:
In the example below, the ternary operator is used to perform time-based greeting.
var hour = new Date().getHours(); var greeting; //time-based gretting greeting = (hour < 18) ? "Good Day!" : "Good Evening";
The output (value of greeting) after running above script will be:
❮ JavaScript - Operators