Search code examples
javascriptconditional-operatorboolean-expression

Order of Operations with ternary operator and OR operator


Why is the order of operations from right to left in the first example?

This evaluates to World

"Hello" || true ? "World" : ""

This evaluates to Hello

"Hello" || (true ? "World" : "")

Solution

  • Probably you know that operations are not executed from left to right, but following the operator priority: just think to:

    1 + 2 * 3
    

    do you expect 7 or 9? As you experimented, ternary operator has the lower priority.

    "Hello" || true ? "World" : ""
    

    is equivalent to

    ("Hello" || true) ? "World" : ""
    

    Hope this helps.