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.

Leave a Comment