JavaScript if(x) vs if(x==true)

后端 未结 2 736
遥遥无期
遥遥无期 2020-12-31 11:49

In JavaScript , in which cases the following statements won\'t be logically equal ?

if(x){}

and

if(x==true){}
2条回答
  •  無奈伤痛
    2020-12-31 12:34

    Several cases evaluate to false in the first form, such as empty string, 0, undefined, null.

    If you want to be a bit more semantic about it, try the bang bang in front of the expression:

    if(!!x){...}
    

    this will convert the expression result to a truthy representing the same semantically. This is closer to an analogue to the expression you describe (x == true)

    Also be aware that == is value comparions with type coercion, eg "3" == 3, whereas === asserts equal typing too.

    So they are not the same, but often logically represent the same test, thanks to the semantics of the language and the !! you can use

提交回复
热议问题