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:

  • 'codescracker'
  • 'hello'
  • '123'

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>

   <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('codescracker') = <span id="resFour"></span></p>

      document.getElementById("resOne").innerHTML = isNaN(40);
      document.getElementById("resTwo").innerHTML = isNaN('40');
      document.getElementById("resThree").innerHTML = isNaN(-40);
      document.getElementById("resFour").innerHTML = isNaN('codescracker');

isNaN(40) =

isNaN('40') =

isNaN(-40) =

isNaN('codescracker') =

In above example, since 40 and -40 are numbers, therefore isNaN() returns false. Whereas since 'codescracker' 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 »

Follow/Like Us on Facebook

Subscribe Us on YouTube