Search code examples
javascriptlogicshort-circuiting

Why does `false && true || true` evaluate to true?


According to MDN Logical Operators page:

false && anything is short-circuit evaluated to false.

Given this information, I would expect false && true || true to evaluate to false. However, this is not the case. The expected result (false) is only given when the statement is written like:

false && (true || true)

A coworker and I have tried to work this out and the closest thing we could come up with is that the statement is being evaluated by order of precedence. According to the MDN Operator Precedence logical-and has a higher precidence over logical-or, suggesting that the condition is evaluated as if false && true were a single statement, which then moves on to determine the boolean condition of false || true which is then true. Written out, this would be:

(false && true) || true

Something is wrong here. It's either the documentation, the JavaScript parsing logic, or my interpretation.

Edit:

I've added a bounty because none of the answers given truly understand the question. As stated above: the MDN Logical Operators page states exactly: "false && anything is short-circuit evaluated to false."

"anything" means "anything"!


Solution

  • Your confusion all comes down to a misunderstanding of precedence.

    A mathematical analogue would be "Zero multiplied by anything equals zero." Consider the following expression:

    0 x 100 + 5
    

    In any programming language, or a decent calculator, this evaluates to 5. The "zero times anything" axiom is true - but the "anything" in this case is 100, NOT 100 + 5! To see why, compare it to this:

    5 + 0 x 100
    

    It doesn't matter whether you add the 5 at the beginning or the end - the operator precedence rules remove ambiguity from the statement.

    In JavaScript boolean logic, && has higher precedence than ||. Since each operator is commutative, writing

    false && true || true
    

    is exactly the same as writing

    true || false && true