Thursday, December 28, 2017

What do I do to sanity check the casting of an int to a string in JavaScript if I'm not supposed to use isNaN?

On the other side of the casting you will end up with NaN if something went wrong and of course NaN is falsey, so just do a check to see if they thing you end up with is either truthy or set to zero which would be the one legitimate falsey scenario for a parsed number. I could swear that I've already blogged of this, but I cannot find it at my own blog because it is such a sprawling mess.

var bar = parseInt(foo);
if(bar || bar === 0) {
   alert("It's good!");
} else {
   alert("It's bad!");
}

No comments:

Post a Comment