How to judge whether a value is Null in JS

foreword

We use the typeof operator when identifying JavaScript primitive types. The Typeof operator can be used on String, Number, Boolean and Undefined types. But when you run typeof null, the result is "object" (logically, you can think of null as an empty object pointer, so the result is "object").

 

 How to judge null

If we need to judge whether the variable temp is null

1. Direct equality comparison

temp === null

The reasons for needing to be triple instead of double are as follows:

①"==" will perform forced conversion, such as:

        100 == "100"  ==>  100 == 100  // true

        "abc" == true  ==>  NaN == 1  // false

② "===" first judge whether it is the same type

  "==" only judges whether the values ​​on both sides of the equal sign are equal, not whether the types are the same. return true if the values ​​are the same

  "===" It is not only necessary to judge whether the values ​​are equal, but also to judge whether the types are the same, that is, only when they are equal can they return true

 If objects are involved:

 when only one side is a reference type

 2. Using logical expressions

if(!tmp && typeof(tmp) != "undefined" && tmp != 0) {

        alert("null");

}

 

Guess you like

Origin blog.csdn.net/qq_42533666/article/details/129190944