Why does isNaN(" ") (string with spaces) equal false?
In JavaScript, why does isNaN(" ")
evaluate to false
, but isNaN(" x")
evaluate to true
?
I’m performing numerical operations on a text input field, and I’m checking if the field is null
, ""
, or NaN
. When someone types a handful of spaces into the field, my validation fails on all three, and I’m confused as to why it gets past the isNaN
check.
Solution 1:
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.
Solution 2:
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 :)
Solution 3:
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
Solution 4:
Try using:
alert(isNaN(parseInt(" ")));
Or
alert(isNaN(parseFloat(" ")));