Why does isNaN(" ") (string with spaces) equal false?

You may find this surprising or maybe not, but here is some test code to show you the wackyness of the JavaScript engine.

document.write(isNaN("")) // false
document.write(isNaN(" "))  // false
document.write(isNaN(0))  // false
document.write(isNaN(null)) // false
document.write(isNaN(false))  // false
document.write("" == false)  // true
document.write("" == 0)  // true
document.write(" " == 0)  // true
document.write(" " == false)  // true
document.write(0 == false) // true
document.write(" " == "") // false

so this means that

" " == 0 == false

and

"" == 0 == false

but

"" != " "

Have fun :)


Try using:

alert(isNaN(parseInt("   ")));

Or

alert(isNaN(parseFloat("    ")));

To understand it better, please open Ecma-Script spec pdf on page 43 "ToNumber Applied to the String Type"

if a string has a numerical syntax, which can contain any number of white-space characters, it can be converted to Number type. Empty string evaluates to 0. Also the string 'Infinity' should give

isNaN('Infinity'); // false

JavaScript interprets an empty string as a 0, which then fails the isNAN test. You can use parseInt on the string first which won't convert the empty string to 0. The result should then fail isNAN.

Tags:

Javascript

Nan