Christophe Debove
Christophe Debove

Reputation: 6296

isNaN() vs. parseInt() confusion

There is something strange.

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

Upvotes: 17

Views: 16045

Answers (2)

Ed Heal
Ed Heal

Reputation: 60007

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

Upvotes: 20

Brian Nickel
Brian Nickel

Reputation: 27550

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

Upvotes: 1

Related Questions