The isNaN() funtion returns true if the value passed was not a number, or false if the value passed was in fact a number. (Remember that "NaN" stands for "Not a Number".) In other words, the isNaN() function will not return an error in case of unexpected argument type, allowing you to elegantly handle the problem.
var attendees = "Four members present";
// Ensure that the value is numerical
if( isNaN(attendees) )
alert("Please enter a number for the number of attendees.");
As expected, our script displayed the error message since the variable tested did not contain a numerical value.
Using the isNaN() Function with Implicit Numerical Values
The isNaN() function is a bit more insightful than first meets the eye: it can determine if a value could be numerical with a proper conversion. A string-quoted number 3 does not yield the expected result.
// Pass a quoted number (string) as argument
alert( isNaN("3.14") );
In other words, the isNaN() function realizes that the quoted string is a number, which can straight-forwardly be converted to a number. As a result, it returned false (i.e. the string passed was in fact a number.)
alert( isNaN(Infinity) ); returns false (meaning that Infinity is numerical).
Don't blindly trust the isNaN() function
In some cases, you will have to deal with free form text entries from a form, which means that you may not have full control over the format in which numbers will be typed into the form. Using only the NaN property or its sibling, the isNaN() function, will accidentally condemn potentially valid inputs:
// Someone filling a form mistakenly typed a space after a number:
var numex = "2 ";
// This time, an unexpanded fraction:
numex = "1/2";
alert( isNaN(numex) ); // JS interpreter fails and returns true
Clean up arguments passed to isNaN() with regular expressions
Here is a quick way to remove any non-digit characters from a string input (like a form field) before passing it to the isNaN() method:
// Here is an inprecise value typed in a form
var numex = "2 I think";
alert( isNaN(numex) ); // returns true (it isn't a number)
// Let's remove any non-digit characters:
numex = numex.replace(/\D/g,""); // numex value is now "2"
alert( isNaN(numex) ); // This time returns false (it is a number)
/\D/g" means "all the non-numbers" - in other words, remove all non-digits by replacing them with an empty string (
Test the isNaN() Function