Open In App

What is the difference between (NaN != NaN) & (NaN !== NaN)?

Improve
Improve
Like Article
Like
Save
Share
Report

NaN as in most programming languages means Not A Number. It belongs to the numeric data types(int, long, short, etc). It represents a numeric value that can not be interpreted as a finite value. That is one can not define its value. The use of NaN is quite rare. NaN is a property of the global object and number object. Its basically use to check the user’s numeric input and thus make the program error-free.
In JavaScript, this question arises that what is the difference between NaN!=NaN and NaN!==NaN? The answer to this question is that for the purpose of NaN, both of them produce the same answer. Both will result in true. This is due to the variable values of NaN. NaN is not equal to NaN.
 

  • Code 1: 
     

javascript




<script type="text/javascript">
var value1 = Math.sqrt( -0.5 );
        document.write("First Value : " + value1 );
var value2 = Math.sqrt( -49 );
        document.write("<br />Second Value : " + value2 );
var boo= value1!==value2
        document.write("<br />Nan!==Nan: "+boo);
var boo= value1!=value2
        document.write("<br />Nan!=Nan: "+boo);
</script>                   


  • Output: 
     
First Value : NaN
Second Value : NaN
Nan!==Nan: true
Nan!=Nan: true

 

  • Code 2: Now in the first example we clearly know that we can not calculate the square root of negative numbers and so it leads to NaN. We can clearly see the output. 
     

javascript




<script type="text/javascript">
var x="Hello";
    document.write("<br />"+ isNaN(x) + "<br />");
var y="World";
    document.write(isNaN(y)+"<br />");
document.write(y!==x);
document.write("<br />");
document.write(y!=x);
</script>                   


  • Output: 
     
true
true
true
true

Now there are two ways of checking the desired input is NaN. The first method to check is isNaN() and the other is Number.isNaN(). The second method is for numeric data types only. the first method is demonstrated in Code 2. The String variable is non-numeric and hence you will get the output as true(i.e. its a NaN).
Difference between NaN!=Nan and NaN!==NaN: 
 

  • The main difference is not on the NaN it’s on the operator single = compare(NaN!=NaN) only the value which is not equal for each NaN
  • In the NaN!==Nan compare the type of the value also so the difference is clear now.

 



Last Updated : 08 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads