Something To Be Aware Of JavaScript isNaN

17th March 2009

The isNaN() function (NaN stands for Not a Number) can be useful if you are looking at form inputs or similar and is used to detect if a value is not a number. For example, the following code shows the output of isNaN() on two variables.

  1. var number42 = "42";
  2. var wibble = "wibble";
  3. alert(isNaN(number42)); // Prints out false
  4. alert(isNaN(wibble)); // Prints out true

This first test is true because the number 42 is, in fact, a number. The second test is false because wibble isn't a number. This is simple enough, but what if we started looking at some different values?

  1. var empty = "";
  2. var nothing = null;
  3. alert(isNaN(empty)); // Prints out false
  4. alert(isNaN(nothing)); // prints out false

What is happening here is that isNaN() tries to converts any value it is given into an number, which means that "" and null get converted to 0 and the function returns false because they are now numbers. You can try this out yourself by doing one of the following:

  1. var empty = "";
  2. alert(+empty); // Prints out 0
  3. alert(Number(empty)); // Prints out 0

To solve this problem you can use the parseInt() function. This takes a string as an input and tries to convert it into a number, if this is not possible then it returns NaN. If parseInt() is given an empty string or a null value it will also return NaN, rather than converting them to 0. This gives us a mechanism by which we can test values using a combination of parseInt() and isNaN().

  1. var empty = "";
  2. alert(isNaN(parseInt(empty))); // Prints out true

Finally, if we give isNaN() and parseInt() an undefined value the results are as follows.

  1. var nothing;
  2. alert(parseInt(nothing) + ", " + isNaN(nothing)); // Prints out NaN, true

The isNaN() function returns true because it can't convert the value into any number.

  1. var nothing;
  2. alert(+nothing);
  3. alert(Number(nothing));

This code prints out NaN for both of the alert statements.

Comments

Permalink
This approach doesn't work. isNaN(parseFloat("-42blah")) returns false, just as "-42" does. I use (isNaN(value) || value == "" || value == null)

Paul Humphreys (Tue, 03/24/2009 - 16:35)

Add new comment

The content of this field is kept private and will not be shown publicly.