Spiga

How to use ternary operator in javascript?

November 06, 08 by Gabi Solomon

The ternary operator will accept three operands and is used to assign a certain value to a variable based on a condition. The syntax is condition ? result1 : result2;

So if the the condition is evalued as true the result1 is runned else result2.

Example:

JavaScript:
  1. <script language=javascript>
  2. var x=3;
  3. (x == 3) ? y="true" : y="false";
  4. document.write(y);
  5. </script>

This will print out: true

Pretty simple, cheers.