Why does short-circuit evaluation work when operator precedence says it shouldn't?

前端 未结 3 952
感动是毒
感动是毒 2021-01-12 05:25

In JavaScript and Java, the equals operator (== or ===) has a higher precedence than the OR operator (||). Yet both languages (JS, Jav

3条回答
  •  轮回少年
    2021-01-12 06:20

    According to the language specification, https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.24

    At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8).

    If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.

    So if you have a || b==c, it is not interpreted as (a || b) == c, because || has lower precedence, as you found in the tutorial. Instead, it is interpreted as a || (b==c). Now since a is the left side of ||, it is evaluated first.

提交回复
热议问题