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

后端 未结 6 2030
遥遥无期
遥遥无期 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:16

    !x will return true for every "falsy" value (empty string, 0, null, false, undefined, NaN) whereas x == null will only return true if x is null (edit: or apparently undefined (see below)).

    Try with x = 0, there is a difference.

    You can say that the NOT operator ! converts a value into its opposite boolean equivalent. This is different than actually comparing two values.

    In addition, if you compare values with ==, JavaScript does type conversion which can lead to unexpected behavior (like undefined == null). It is better to always use strict comparison === (value and type must be the same) and make use of type conversion only if you really know what you are doing.

    Something to read:

    • Data Type Conversion
    • Comparison Operators
    • Logical Operators

    Update:

    For more information about the non-strict comparison of null and undefined (or the comparison in general), it is worth having a look at the specification. The comparison algorithm is defined there (the comparison is x == y):

    1. If Type(x) is the same as Type(y), then
      (...)
    2. If x is null and y is undefined, return true.
    3. If x is undefined and y is null, return true.
    4. (...)

    (...)

提交回复
热议问题