Why does !!1==“1” equal true and !!2==“2” equal false?

后端 未结 5 1452
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 15:47

As the title states, why does:

> !!1==\"1\"

equal

True

and

> !!2==\"2\"
         


        
5条回答
  •  无人及你
    2020-12-07 16:09

    Its a precedence operator problem.

    The ! operator is an unary operator. That means the left side must be an expression or a boolean evaluable section. See Javascript MDN.

    !!1==1 is not necessary !!(1==1)
    !!2==2 is not necessary !!(2==2)
    

    I think that these expressions should be consistent if the equal operator has more precedence than ! operator. But if we consider the opposite, evaluating first negations we have:

    !!1 == 1
    !1 -> false
    !!1 -> true
    !!1 == 1 
    

    And with the two

    !!2==2
    !2 -> false
    !!2 -> true
    (!!2) == 2 -> false
    

    That is because the ! operator has precedence over == operator

    See Mozilla Operator Preference

提交回复
热议问题