Spiga

How to use ternary operator in javascript?

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.

Related Posts

  • Also when describing how to use the ternary operator putting
    var y = (x == 3);
    Is pretty useless Regardless of Boolean or String.
    var y = (x == 3) ? true : false;
    is the best example as it shows the user full use of the ternary including using for assignment.
    The original example could be edited to
    (x == 3) ? y="true" : z="true";
    So the user can see that the operator is used to assign values to multiple variables.
  • j87
    It may be clearer to use "var y = (x == 3);", but not the same. In the example, y is being assigned a string value "true" or "false", not the boolean values true or false. i.e.

    <script language=javascript>
    var x = 3;
    var y = (x == 3) ? "true" : "false";
    var z = (x == 3);
    a = z==y ? true : false;
    document.write(y + " " + z + " " + a);
    </script>

    results in "true true false"
    being that (true != "true")
  • What SALZ` said is the better, cleaner way.
  • what about:

    var y = (x == 3) ? true : false;

    or just

    var y = (x == 3);
blog comments powered by Disqus