Conditional Operator ( ? : ) operator in Javascript
The conditional ? : operator is an alternative to the if else javascript statement. It creates a very small code of what an if else statement would take. Javascript borrows this trend of brevity from C programming language.
To understand the conditional operator using ? : consider the following code written with if else. The code computes the minimum of two numbers x and y.
|
These six lines of codes can be replaced with a single line of code.
min = (x < y ) ? x : y;
(x < y ) ? x : y; is an expression which returns one of two values, x or y. The condition, (x < y), is tested. If it is true the first value, x, is returned. If it is false, the second value, y, is returned. Whichever value is returned is dependent on the conditional test, x
The conditional ? : operator is called ternary operator and its general syntax olooks like
result = testCondition ? value1 : value2
If testCondition is true, result is assigned value1; otherwise, result is assigned value2.
Here is the complete javascript example that prints the min of three numbers using ternary conditional statement.
|
If you compile and run, you get the following output
Minimum of three numbers is 18 |
You may like to try this example online here
Exercise
Change the above code so that instead of minima of two numbers, it prints the maxima of the two numbers