My WAT? moment using javascript function parseInt()


Heads up!

The blog has moved!
If you are interested in reading new posts, the new URL to bookmark is


I know a good developer should always read the manual, but sometimes somebody is  just brave enough to start coding withouth caring to read it all… and that’s how I ended up having my “WAT?” moment using the function parseInt().

I was trying to create a Date object from a json serialized data sent by the server, using parseInt() to transform the day, the month and the year into an int. For several data points the process was successfull, whereas for just a few it was not and I could not understand why… until I pointed Chrome debugger to the right line of code and found out that parseInt has a funny behaviour if we do not specify the radix.

Let me show you what I mean: if you type each of the following line into Chrome developer console, the result you’ll get is what comes after the “–>”

parseInt(“01”) –>1
parseInt(“02”) –>2
parseInt(“03”) –>3
parseInt(“04”) –>4
parseInt(“05”) –> 5
parseInt(“06”) –> 6
parseInt(“07”) –> 7
parseInt(“08”) –> 0
parseInt(“09”) –> 0
It comes out that
If the input string begins with “0”, radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10).  For this reason always specify a radix when using parseInt. (
Ok I got it, always specify the radix like parseInt(“08”, 10)  to avoid unexpected results.
I just have one last doubt… how in the world 9 mod 8 is equal to 0? Even Google confirms it’s wrong (try for yourself typing 9 mod 8 in the search box)!

One thought on “My WAT? moment using javascript function parseInt()

  1. dave mcdave

    it’s not 9 mod 8, it’s 9 *base* 8. Base 8 doesn’t have a digit 9 so it’s just an error. This isn’t modulo arithmetic, it’s a whole new interpretation of the number string.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s