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.

  1. if (x < y) {
  2. min = x;
  3. }
  4. else {
  5. min = y ;
  6. }


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.
  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. <!--
  5. /*
  6. ********************************************************
  7. Example ternary conditional operator
  8. ********************************************************
  9. */
  10.  
  11. var x = 21;
  12. var y = 24;
  13. var z = 18;
  14. var min;
  15.  
  16. min = (x < y ) ? x : y ;
  17. min = (min < z ) ? min : z ;
  18.  
  19. document.write("Minimum of three numbers is "+ min);
  20. //-->
  21. </script>
  22. </body>
  23. </html>


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