Skip to content

isNaN JavaScript function | Check value is NaN(Not a Number)

  • by

The isNaN() Function used to determine whether the passed value is NaN(Not a Number)/illegal number in JavaScript. The global isNaN() function, converts the tested (given) value to a Number, then tests it.

Syntax

isNaN(value)

Parameter Values

The value which is to be tested for NaN.

Return Value

This function returns true if the value equates to NaN else it returns false.

Examples of isNaN() JavaScript function

Let’s see the different example code of isNaN() function.

Pass the number as Parameter

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 
    	var num = 700; 
        document.write("Output : " + isNaN(num));           
    </script> 
      
    
</body> 
  
</html> 
Examples of isNaN JavaScript function

Equation resulting in the infinite value

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 
    	var num=0/0; 
        document.write("Output : " + isNaN(num));           
    </script> 
      
    
</body> 
  
</html> 

Output : true

Pass the string as a parameter value

<script type="text/javascript"> 
    var test='hello'; 
    document.write("Output : " + isNaN(test));           
</script>

Output : false

Pass NaN

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 
    var check=NaN; 
         document.write("Output : " + isNaN(check));           
      </script> 
      
    
</body> 
  
</html> 

Output : ture

Q: How to remove NaN error in JavaScript?

Answer: You can use if conditions with isNaN() function to remove Nan error:

Note: Number.isNaN() doesn’t convert the values to a Number.

<!DOCTYPE html> 
<html>
  
<body> 
    <script> 
    num = NaN; 
    if(isNaN(num)) num = 0; 
    alert(num); 
</script> 
      
    
</body> 
  
</html> 

Read more: Convert NaN to 0 in JavaScript | Using isNan() method OR other method

Q: What does mean number.isnan(value) is not a function?

Answer: Number.isNaN(x) checks if x is directly evaluated to NaN or not.

The key difference between the two is that the global isNaN(x) the function performs a conversion of the parameter x to a number.

Q: Difference between isNaN and Number.isNaN in javascript?

Answer: Here is differentiations:-

  • isNaN converts the argument to a Number and returns true if the resulting value is NaN.
  • Number.isNaN does not convert the argument; it returns true when the argument is a Number and is NaN.

Do comment if you have any questions and suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *