How to turn NaN from parseInt into 0 for an empty string?
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.
The problem
Other answers don't take into account that 0
is falsy, and thus the following will be 20 instead of 0:
const myNumber = parseInt('0') || 20; // 20
The solution
I propose a helper function, that solves most of the issues:
function getNumber({ value, defaultValue }) {
const num = parseInt(value, 10);
return isNaN(num) ? defaultValue : num;
}
The helper function will give the following results:
getNumber({ value: "0", defaultValue: 20 }); // 0
getNumber({ value: "2", defaultValue: 20 }); // 2
getNumber({ value: "2.2", defaultValue: 20 }); // 2
getNumber({ value: "any string", defaultValue: 20 }); // 20
getNumber({ value: undefined, defaultValue: 20 }); // 20
getNumber({ value: null, defaultValue: 20 }); // 20
getNumber({ value: NaN, defaultValue: 20 }); // 20
getNumber({ value: false, defaultValue: 20 }); // 20
getNumber({ value: true, defaultValue: 20 }); // 20
For people who are not restricted to parseInt
, you can use the bitwise OR operator (which implicitly calls ToInt32
to its operands).
var value = s | 0;
// NaN | 0 ==>> 0
// '' | 0 ==>> 0
// '5' | 0 ==>> 5
// '33Ab' | 0 ==>> 0
// '0x23' | 0 ==>> 35
// 113 | 0 ==>> 113
// -12 | 0 ==>> -12
// 3.9 | 0 ==>> 3
Note: ToInt32
is different from parseInt
. (i.e. parseInt('33Ab') === 33
)