[removed] What is the difference between `if (!x)` and `if (x == null)`?

后端 未结 6 2027
遥遥无期
遥遥无期 2020-12-08 05:18

What is the difference between if (!x) and if (x == null); that is, when can their results be different?

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 06:00

    Say x is a string.

    x = undefined;
    if(!x) {
       alert("X is not a truthy value");
    }
    if(x == null) {
       alert("X is null");
    }
    
    x = "";
    if(!x) {
       alert("X is not a truthy value");
    }
    if(x == null) {
       alert("X is null");
    }
    
    x = null;
    if(!x) {
       alert("X is not a truthy value");
    }
    if(x == null) {
       alert("X is null");
    }
    

    You'll notice that "X is not a truthy value" is shown in all three cases, but only in the case of X being undefined or null is "X is null" shown.

    When X is a boolean value, then (!x) will be true when X is false but (x == null) will not be. For numbers 0 and NaN are considered false values, so not X is truthy.

    See it in action, including the difference between == (equality using type conversion) and === (strict equality)

提交回复
热议问题