JavaScript: parseInt() Tip to avoid NaN

There is a Mobile Optimized version of this page (AMP). Open Mobile Version.

parseInt() is an incredibly useful function which is available in some form in all programming languages, however in JavaScript there is one slightly annoying difference…

Unlike in other languages which either throw an error or just assume 0 when a string cannot be converted to an integer, parseInt() returns "NaN" which means "Not-a-Number". This is incredibly irritating when you have a nested loop for instance doing parseInt() and incrementing to a integer, because incrementing NaN makes the value of the variable "NaN".

There is a function that can check for NaN called isNaN() but I have another approach which is cleaner and simpler to use throughout your code.

var myStr = "NotaNumber";

var myNum = 3;

myNum += parseInt(myStr) || 0;

The key is the "|| 0", basically, if parseInt() does not return a number the || operator is invoked which then returns 0 instead. Very clean and only 3 more characters than normal.

Now you will just have to figure out why the returned values are 0 and not what you expected Winking smile.

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips