(true + false) > 2 + true; Why does this return false?

后端 未结 3 826
再見小時候
再見小時候 2021-01-06 22:06

Im studying javascript and can\'t figure it out why this line returns false:

(true + false) > 2 + true
相关标签:
3条回答
  • 2021-01-06 22:25

    That's because your code evaluates to :

    1 + 0 > 2 + 1
    

    Which is equivalent to :

    1 > 3
    

    This is due to the way that Javascript is evaluated and interpreted by the Javascript engine when you are using arithmetic operators on some types, such as booleans, which are implicitely converted, in this case, to numbers.

    0 讨论(0)
  • 2021-01-06 22:36

    The reason is called type coercion; You're using two boolean values in an arithmetic operation which is not feasible unless the interpreter converts them into numbers first.

    true --> 1 false --> 0

    Try it yourself; type +true and you will get 1;

    0 讨论(0)
  • 2021-01-06 22:39

    true equals 1. false equals 0.

    So your expression is equivalent to:

    (1 + 0) > 2 + 1
    

    which reduces to

    1 > 3
    

    which is false!

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