NaN is not equal to NaN

Posted Jun 27, 20201 min read

I don t know how much this little knowledge point is used. I have seen it in the book, so I have some impressions. I wrote a code similar to the following some time ago

var result;
if(parseInt('abc')==NaN) {
  return "equal";
} else {
  return "Not equal";

After the breakpoint debugging, I found that they are not equal anyway. The result returned by the method parseInt() is indeed NaN, but the result returned by the comparison with the NaN on the right is false. At this time, I suddenly remembered that NaN has characteristics that are not equal to itself. So simply collect the data and organize

the reason

Before we understand the reason, let s clarify a question. When does NaN appear? In theory, there are two cases

  • Expression calculation
  • Type conversion

We analyze one by one

Expression evaluation

When operators such as +-*/are used in the operation, js will automatically convert it. The variable involved in the calculation will be converted to the Number type, which is one of the basic types of js. If the conversion fails, NaN will be returned. For example:

console.log(12 +'a'); //NaN

Type conversion

The most typical is the parseInt() used in the original example, in addition to parseFloat() and Number(), the result of passing in a non-numerical variable is NaN, which is well understood. By the way, parse series methods and Number()slightly different.

parseInt('123abc'); //123
Number('123abc'); //NaN

to sum up

From the above two cases of generating NaN, NaN is an abnormal result, that is, "not a number", although it is also a variable, but it is a descriptive variable,'a' is not a number(not a number),'b' is not a number(not a number), but'a' and'b' are not equal, so NaN != NaN is also established.