Wednesday, May 19, 2010

Base Dependency, JavaScript and how parseInt() returns 0

I learned today that the parseInt() function in JavaScript actually has a second parameter that is optional. This second parameter defines the number's base. Thus, you can parse an integer that is binary, octal and hexadecimal. However, if you do not define the base, the parseInt function takes a guess at the base instead of defaulting to decimal.

So, if you have a parseInt('08') or parseInt('09'), the function will return 0. This is because it is guessing that these are octal numbers (based on the 0 in front) and then returns a 0 because they are invalid octal numbers.

The fix is simple, define the base. Use parseInt('08',10) or parseInt('09',10) instead. This blog post helped me and has more info on the matter.

No comments: