Is it possible somehow to return 0 instead of NaN
when parsing values in JavaScript?
In case of the empty string parseInt
returns NaN
.
Is it possible to do something like that in JavaScript to check for NaN
?
var value = parseInt(tbb) == NaN ? 0 : parseInt(tbb)
Or maybe there is another function or jQuery plugin which may do something similar?
var s = '';
var num = parseInt(s) || 0;
When not used with boolean values, the logical OR ||
operator returns the first expression parseInt(s)
if it can be evaluated to true
, otherwise it returns the second expression 0
. The return value of parseInt('')
is NaN
. NaN
evaluates to false
, so num
ends up being set to 0
.
You can also use the isNaN()
function:
var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)
I was surprised to not see anyone mention using Number()
. Granted it will parse decimals if provided, so will act differently than parseInt()
, however it already assumes base 10 and will turn "" or even " " in to 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With