Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isNaN() vs. parseInt() confusion

Tags:

javascript

There is something strange.

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

like image 598
Christophe Debove Avatar asked Nov 25 '11 16:11

Christophe Debove


2 Answers

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

like image 124
Ed Heal Avatar answered Oct 24 '22 12:10

Ed Heal


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

like image 33
Brian Nickel Avatar answered Oct 24 '22 12:10

Brian Nickel