Something To Be Aware Of JavaScript isNaN

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.

var number42 = "42";
var wibble = "wibble";
alert(isNaN(number42)); // Prints out false
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?

var empty = "";
var nothing = null;
alert(isNaN(empty)); // Prints out false
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:

var empty = "";
alert(+empty); // Prints out 0
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().

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

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

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

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

var nothing;
alert(+nothing);
alert(Number(nothing));

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

Comments

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

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
7 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.