Using The isNaN() Function in JavaScript, With Examples

JavaScript isNan()

isNaN() is a JavaScript function that will tell you whether a value is equal to NaN – or Not a Number. It can be used to determine whether the result of a mathematical operation is valid or not. Here’s how to use it.

What is NaN?

  • NaN is a special value that means Not a Number.
  • It means that a value that should be a number could not be parsed as a number.
  • Any mathematical operation between any other value and NaN will result in NaN.
  • It usually means something has gone wrong with a number parsing or mathematical operation and that you need to check your code or handle input differently.

NaN was also explored in our article on the JavaScript parseInt() function.

JavaScript isNaN() Function Syntax

The isNaN() function will check whether a value or variable has a value equal to NaN when JavaScript tries to parse it as a number.

Here’s the syntax for the isNaN() function in JavaScript:

isNaN(VALUE)

Note that:

  • VALUE is a value, or variable, to check
  • isNaN() will return a boolean value (TRUE or FALSE)
    • It will return TRUE if VALUE is equal to NaN after JavaScript has attempted to parse it as a number and FALSE if otherwise

Examples

var myNumber = 4.32;

var myString = "foo";

var myNumberString = "1234";

var myNaN = NaN;

console.log(isNaN(undefined)); // true - undefined evaluates as NaN

console.log(isNaN(myNumber)); // false - 4.32 evaluates as a number

console.log(isNaN(myString)); // true - the given string "foo" cannot be parsed as a number

console.log(isNaN(myNumberString)); // false - "1234" is a string which can be parsed as a number

console.log(isNaN(myNumber * myString)); // true - the result of multiplying 4.32 and "foo" could not be calculated as a number

console.log(isNaN(myNaN)); // true - the value is already NaN

console.log(isNaN(2 * myNumber)); // false - the multiplication result of two numbers is a number

console.log(isNaN(myNumber * myNaN)); // true - as the result of any maths involving NaN is NaN

console.log() is used to output the return value of each example of isNaN().

For more information, check out the Mozilla developer documentation.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

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