Something To Be Aware Of JavaScript isNaN
Published by philipnorton42 on Tue, 03/17/2009 - 12:54The 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 2 3 4 | 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?
1 2 3 4 | 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:
1 2 3 | 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().
1 2 | var empty = ""; alert(isNaN(parseInt(empty))); // Prints out true |
Finally, if we give isNaN() and parseInt() an undefined value the results are as follows.
1 2 | 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.
1 2 3 | var nothing; alert(+nothing); alert(Number(nothing)); |
This code prints out NaN for both of the alert statements.
Comments
This approach doesn't work.
Paul Humphreys (not verified) - Tue, 03/24/2009 - 17:35Add new comment