Javascript Number Type NaN

Introduction

NaN is short for Not a Number.

NaN indicates that an operation intended to return a number has failed.

For example, dividing any number by 0 returns NaN.

Any operation involving NaN always returns NaN.

NaN is not equal to any value, including NaN.

For example, the following returns false:

console.log(NaN == NaN);  // false 

Javascript provides the isNaN() function.

This function determines if the value is "not a number."

When a value is passed into isNaN(), it will be converted into a number.

Some nonnumerical values convert into numbers directly, such as the string "10" or a Boolean value.

Any value that cannot be converted into a number causes the function to return true.

console.log(isNaN(NaN));     // true 
console.log(isNaN(10));      // false - 10 is a number 
console.log(isNaN("10"));    // false - can be converted to number 10 
console.log(isNaN("asdf"));  // true - cannot be converted to a number 
console.log(isNaN(true));    // false - can be converted to number 1 

This example tests five different values.

The first test is on the value NaN itself, returns true.

The next two tests use numeric 10 and the string "10", which both return false because the numeric value for each is 10.

The string asdf, however, cannot be converted into a number, so the function returns true.

The Boolean value of true can be converted into the number 1, so the function returns false.

isNaN() can be applied to objects.

In that case, the object's valueOf() method is first called to determine if the returned value can be converted into a number.

If not, the toString() method is called and its returned value is tested as well.




PreviousNext

Related