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.
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.