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; }

No comments yet.

Leave a Comment

All fields are required. Your email address will not be published.

Recent JavaScript Tutorials

JavaScript if-else Ternary Operator

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

JavaScript do…while Loop

do...while loop in JavaScript works like while loop in JavaScript the only difference is that do block executes at least once before while loop’s test condition. That’s why do block ...

JavaScript while Loop

while loop in JavaScript works same like for loop in JavaScript but in a little bit different manner. while loop runs until the condition is true and exits when the ...

JavaScript for Loop

for loop in JavaScript is most often used to execute a block of code with different value each time. So, to reduce the code length instead of adding number of ...

JavaScript switch-case Statement

To execute a single block of code satisfying a condition in case statement of JavaScript switch-case is used. break keyword is used in every case statement to exit the switch ...

Recent Comments