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.




This will print out: true

Pretty simple, cheers.

  • http://salzsee.info Salz`

    what about:

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

    or just

    var y = (x == 3);

  • http://originalcopy-on.blogspot.com OriginalCopy

    What SALZ` said is the better, cleaner way.

  • http://www.jeremywillemse.co.nz/ 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);

    results in “true true false”
    being that (true != “true”)

  • http://www.jdesign.org.uk/ James

    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.