JavaScript Operator Precedence

前端 未结 2 818
一向
一向 2021-01-29 07:30

According to Mozilla, the === operator has higher precedence than the || operator, which is what I would expect.

However this statement evaluates to the number 1, rathe

相关标签:
2条回答
  • 2021-01-29 08:15

    || is a short circuit operator and conditions are evaluated from left to right.
    So here : left || right, if the left condition is true, the whole condition is evaluated to true and the right one is never evaluated.

    Here :

    let x = 1 || 0 === 0; // x === 1;
    

    x = 1 assigns 1 to x and the second condition after || is never evaluated as if (1) is evaluated to true.

    And here :

    let x = (1 || 0) === 0; // x === false;
    

    (1 || 0) is evaluated to true as if (1) is still evaluated to true.
    And then true === 0 is evaluated to false.
    So x is valued to false.

    0 讨论(0)
  • 2021-01-29 08:35

    Higher operator precedence is like a parenthesis around the operands.

    let x = 1 || (0 === 0);
    

    The second part gets never evaluated, because of the truthy value of 1 .

    0 讨论(0)
提交回复
热议问题