The JavaScript conditional ternary operator is considered as shorthand for if-else statement that is frequently used to return the result in single code statement. It takes three operands to return a result, starting from a condition followed by a question mark ?
then an expression if condition is true followed by a colon :
and then an expression if the condition is false.
Syntax
condition ? (expression-if-true) : (expression-if-false)
condition: any expressions that could considered as true or false.
expression-if-true: an expression that is to be evaluated if condition is true.
expression-if-false: an expression that is to be evaluated if condition is false.
Example
var x = 10; var y = 20; var z = x > y ? x : y;
Ternary Operator Chaining
The ternary operator can also be used to perform if...else-if...else
chaining also.
Example
var x=10; var y=20; var z = x + y > 20 ? y : y - x < 20 ? x : y/x > 5 ? y : x;
It’s equivalent to
if(x + y > 20) { return y; } else if(y - x < 20) { return x; } else if(y/x > 5) { return y; } else { return x; }