How to turn NaN from parseInt into 0 for an empty string?

How to turn NaN from parseInt into 0 for an empty string?

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?

Solutions/Answers:

Solution 1:

var s = '';

var num = parseInt(s) || 0;

Solution 2:

You can also use the isNaN() function:

var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)

Solution 3:

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.

Solution 4:

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)

Solution 5:

The problem

Related:  How can I run multiple npm scripts in parallel?

Other answers don’t take into account that is falsy, and thus the following will be 20 instead of 0:

var myNumber = parseInt('0') || 20; // 20

The solution

I propose a helper function, that solves most of the issues:

function getNumber(number, defaultNumber) {
    return isNaN(parseInt(number, 10)) ? defaultNumber : parseInt(number, 10);
}

The helper function will give the following results:

getNumber('0', 20); // 0
getNumber('2', 20); // 2
getNumber('2.2', 20); // 2
getNumber('any string', 20); // 20
getNumber(undefined, 20); // 20
getNumber(null, 20); // 20
getNumber(NaN, 20); // 20
getNumber(false, 20); // 20
getNumber(true, 20); // 20

Solution 6:

var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);