Methods to determine null undefined and NaN in JS

  • 2020-03-30 02:26:01
  • OfStack

I wrote STR ="s"++;

And then Nan comes up and looks around for a while.

The data collected are judged as follows:

1. The judge undefined:


var tmp = undefined; 
if (typeof(tmp) == "undefined"){ 
alert("undefined"); 
}

Typeof returns a string, with six possibilities: "number", "string", "Boolean", "object", "function", "undefined"

2. Determine null:


var tmp = null; 
if (!tmp && typeof(tmp)!="undefined" && tmp!=0){ 
alert("null"); 
}

3. The judge NaN:


var tmp = 0/0; 
if(isNaN(tmp)){ 
alert("NaN"); 
}

Note: if NaN is compared to any value, including itself, the result is false, so you cannot use the == or === operator to determine whether a value is NaN.

Tip: the isNaN() function is often used to detect the results of parseFloat() and parseInt() to see if they represent valid Numbers. Of course, you can also use the isNaN() function to detect arithmetic errors, such as when 0 is used as a divisor.

4. Undefined and null:


var tmp = undefined; 
if (tmp== undefined) 
{ 
alert("null or undefined"); 
}

var tmp = undefined; 
if (tmp== null) 
{ 
alert("null or undefined"); 
}

Description: null = = is undefined

< ! -- EndFragment -- >

5. Undefined, null and NaN:


var tmp = null; 
if (!tmp) 
{ 
alert("null or undefined or NaN"); 
}

Tip: it's usually not enough to distinguish between the two.


Related articles: