JavaScript Operator Precedence

前端 未结 2 819
一向
一向 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.

提交回复
热议问题