17

There is something strange.

Why
with isNaN("") I get False
But
with parseInt("") I get NaN
?

hugomg
  • 68,213
  • 24
  • 160
  • 246
Christophe Debove
  • 6,088
  • 20
  • 73
  • 124
  • 2
    Possible duplicate of http://stackoverflow.com/questions/825402/why-does-isnan-equal-false –  Nov 25 '11 at 16:28
  • Because `isNaN` doesn't use `parseInt`? – Dave Newton Nov 25 '11 at 16:30
  • 1
    The key is to understand the difference between **type conversion** and **parsing**, `isNaN` behind the scenes, will do type conversion of its argument to the `Number` type, while `parseInt` will try to *parse* the string provided. See also: http://stackoverflow.com/questions/4090518/string-to-int-use-parseint-or-number – Christian C. Salvadó Nov 25 '11 at 16:39
  • Does this answer your question? [Why does isNaN(" ") (string with spaces) equal false?](https://stackoverflow.com/questions/825402/why-does-isnan-string-with-spaces-equal-false) – phuzi Dec 09 '20 at 12:32

2 Answers2

20

isNaN takes an integer as an argument - therefore JS converts "" to 0

parseInt takes a string as an argument - therefore an empty string is not a number

Aditya Singh
  • 15,810
  • 15
  • 45
  • 67
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • already answered - duplicate http://stackoverflow.com/questions/825402/why-does-isnan-equal-false –  Nov 25 '11 at 16:32
  • 11
    `isNaN` doesn't take an "integer", it *expects* a Number (which are all IEEE-754 doubles, e.g. `isNaN(0.5)` yields `false`), that's why it tries to *type convert* the argument value to Number – Christian C. Salvadó Nov 25 '11 at 16:33
1

This is because "" is equivalent to zero in JavaScript. Try "" == 0. This means if you try evaluating it in a numerical equation, it will come up as 0. When you parse it on the other hand it realizes there is nothing there.

As an alternative to parseInt you could use Math.floor. This will give you 0 for "".

Brian Nickel
  • 26,890
  • 5
  • 80
  • 110