1. Computing & Technology

JavaScript By Example

Functions: 3. isNaN

From , former About.com Guide

This function tests whether the value passed to it is or isn't a number - it returns false if it is a number and true if it isn't.

It is possible for calculations on numbers to give results that are not numbers (at least in so far as JavaScript is concerned) such as dividing by zero or taking the square root of a negative number. There isn't much point in testing the value returned from a parseInt or parseFloat to see if it is a number or not though because those functions always return a number even if it isn't the number you expected. It might be worth testing the string you are inputting to either of those functions though (if the number is supposed to be base 8, 10, or 16 only for parseInt) as that can then ensure that there isn't anything on the end that is being discarded.

Here's our last example with the code added to test that it actually is a number that we are passing into parseFloat. Of course since the function itself tests if something is "not a number" we need a double negative to test if it in fact is a number.


var googol, str;
str = '+1.0e+100';
if (!isNaN(str))
  googol = parseFloat(str);

Reader Submissions: Help Others By Providing Your Own JavaScript Examples

JavaScript By Example

©2012 About.com. All rights reserved.

A part of The New York Times Company.