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

后端 未结 2 739
遥遥无期
遥遥无期 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:29

    They are not at all equal.

    if (x)
    

    checks if x is Truthy where as the later checks if the Boolean value of x is true.

    For example,

    var x = {};
    if (x) {
        console.log("Truthy");
    }
    if (x == true) {
        console.log("Equal to true");
    }
    

    Not only an object, any string (except an empty string), any number (except 0 (because 0 is Falsy) and 1) will be considered as Truthy, but they will not be equal to true.

    As per ECMA 5.1 Standards, in if (x), Truthiness of x will be decided, as per the following table

    +-----------------------------------------------------------------------+
    | Argument Type | Result                                                |
    |:--------------|------------------------------------------------------:|
    | Undefined     | false                                                 |
    |---------------|-------------------------------------------------------|
    | Null          | false                                                 |
    |---------------|-------------------------------------------------------|
    | Boolean       | The result equals the input argument (no conversion). |
    |---------------|-------------------------------------------------------|
    | Number        | The result is false if the argument is +0, −0, or NaN;|
    |               | otherwise the result is true.                         |
    |---------------|-------------------------------------------------------|
    | String        | The result is false if the argument is the empty      |
    |               | String (its length is zero); otherwise the result is  |
    |               | true.                                                 |
    |---------------|-------------------------------------------------------|
    | Object        | true                                                  |
    +-----------------------------------------------------------------------+
    

    Note: The last line object, which includes both objects and Arrays.

    But in the later case, as per The Abstract Equality Comparison Algorithm,

    If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
    If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
    

    value of x will be converted to a number and that number will be checked against true.

    Note:

    In JavaScript, true is 1 and false is 0.

    console.log(1 == true);
    # true
    console.log(0 == false);
    # true
    

提交回复
热议问题