A Quick JavaScript Gotcha: parseInt

Friday, September 04 2009

A co-worker recently shed the light on an interesting “feature” of JavaScript’s parseInt function. parseInt actually takes in a second parameter in addition to the string you are trying to parse: The base number system you are attempting to convert to. If you do not specify a second parameter, JavaScript will try to derive the base system from the input string. This can lead to some very unexpected results when, for example, one has parseInt(“010”). In this example, the number 8 is returned since it was interpreted to be an octal number.

To prevent this from happening, always be sure to specify base 10 when using parseInt() in JavaScript.