JavaScript NaN (Not a Number) with Examples

This post is published to provide information regarding the NaN in JavaScript like:

What is NaN?

NaN stands for Not-a-Number, refers to a value which is not a JavaScript valid number. For example:

Check whether a Value is NaN

In JavaScript, to check whether a specified value is NaN, use isNaN() method. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>isNaN(40) = <span id="resOne"></span></p>
   <p>isNaN('40') = <span id="resTwo"></span></p>
   <p>isNaN(-40) = <span id="resThree"></span></p>
   <p>isNaN('fresherearth') = <span id="resFour"></span></p>

   <script>
      document.getElementById("resOne").innerHTML = isNaN(40);
      document.getElementById("resTwo").innerHTML = isNaN('40');
      document.getElementById("resThree").innerHTML = isNaN(-40);
      document.getElementById("resFour").innerHTML = isNaN('fresherearth');
   </script>
   
</body>
</html>
Output

isNaN(40) =

isNaN('40') =

isNaN(-40) =

isNaN('fresherearth') =

In above example, since 40 and -40 are numbers, therefore isNaN() returns false. Whereas since 'fresherearth' is not a number, therefore isNaN() returns true.

Plase note: Since isNaN() method converts the specified value to a number first, before testing. Therefore in case of isNaN('40') the value '40' gets converted into a number, which will be 40, then tested whether it is Not-a-Number or not.

JavaScript Online Test


« Previous Tutorial Next Tutorial »