Why does an assignment in an if statement equate to true?

不问归期 提交于 2019-12-02 10:18:36

There's a difference between making an abstract equality comparison with == and performing a simple type cast to boolean from a number value. In a == comparison between a boolean and a number, the boolean value is converted to 0 or 1 before the comparison. Thus in

if (true == 2)

the value true is first converted to 1 and then compared to 2.

In a type cast situation like

if (x = 2)

the number is converted to boolean such that any non-zero value is true. That is, the value 2 is assigned to x and the value of the overall expression is 2. That is then tested as boolean as part of the evaluation of the if statement, and so is converted as true, since 2 is not 0.

The various values that evaluate to boolean false are 0, NaN, "", null, undefined, and of course false. Any other value is true when tested as a boolean (for example in an if expression).

Why does an assignment in an if statement equate to true?

It doesn't. An assignment is evaluated as whatever value is assigned.

This expression is a true value:

a = true

But this expression is a false value:

b = false

That's true whether or not you put it in an if statement or not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!