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

IVR Avenger picture IVR Avenger · May 5, 2009 · Viewed 70.2k times · Source

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.

Answer

Antonio Haley picture Antonio Haley · May 5, 2009

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.