1

Topic: An int is an int is an int...isn't it?

For some reason I'm considered the "JavaScript Guru" where I work, which I suppose is a sort of honor in a company that large. Another employee (let's call him "Bob") asked me to come down and help him solve a problem he was having with a bit of JavaScript.

I came down, and he explained what he was trying to do. He had a date (08/14/2008) coming in as simple text, and needed to break it apart into month/day/year. So he took the first two characters of his date to get the month, the 4th and 5th characters for the day, and so on. He was then converting those smaller bits of text into numbers ("08" into 8, "14" into 14, etc.). Problem is, he was getting zero for the month.


Some of you may have already guessed that he was doing the following to get his numbers:

var month = parseInt(monthString);

Instead of eight, it was returning zero. As soon as I saw it, I remembered the last time that had snuck up and bitten me in the butt. I changed his code to:

var month = parseInt(monthString, 10);

...and it gave him the eight he expected.

Oddly, most examples of parseInt you'll find on the web completely skip the second parameter: the radix. The radix tells parseInt what number base to use. So a binary example might be:

var num = parseInt('010110', 2);

And of course you could use it to convert hexadecimal:

var num = parseInt('8AFA', 16);

But, you ask, why does "08" come up as zero when you don't specify a radix? Shouldn't it default to 10, like any human would expect?

What it actually does when you don't specify the radix is try to guess based on the text you give it. And when you remember that JavaScript takes quite a bit from C, it starts to make sense. In C, if you start a number with "0x", then it's read as hexadecimal. If you start with a zero, it interprets it as octal (base 8). Really, this is all a carryover from C. "08" has a leading zero, so it's treated as octal, but there is no "8" in octal...it only goes from zero to seven. So you get a zero back. You'll get the same thing from "09". Extra credit if you know what "010" will get you!

This is one of those sneaky things that can really bite you when you least expect it. Awareness can save you, but so can using a JavaScript framework like jQuery, or MooTools. They have helper functions to handle this for you in a standard way. Either way, you should now know how to keep this from biting you in your own code.

Are you playing?
http://www.atomicmonks.com/sig.php?a=av&pname=Brother%20Erryn