How often do you use parseInt in your javascript applications? Have you noticed some strange behavior of the same?

If you notice carefully you can find parseInt(“08”) and parseInt(“09”) return value 0 instead of 8 and 9. This might lead to serious problems if you continue to ignore it.

FACTORS BEHIND THIS

In Javascript, the parseInt() function takes two arguments, the first one is the string to be parsed (which is a compulsory argument) and the second one is a radix value, which is an optional argument. Defining the radix we specify the conversion type i.e. binary, hexadecimal, octal, and decimal.

Mostly we do not use the radix argument while using parseInt() and the function remains unaware about the conversion type i.e. whether you want a decimal (base 10) conversion or not. By default it treats it as an octal value instead of a decimal and tries to apply the conversion accordingly.

Octal is of base 8, and it only identifies digits from 0-7 as valid numbers. So, “08” and “09” are treated as invalid numbers as they do not fall within the Octal range.

SOLUTION

Always provide the second argument i.e. the radix as 10

parseInt(“09”, 10);

This will return the output as 9 instead of 0.

Kaushik Mohanty , JavaScript Programmer, Mindfire Solutions.

Related Tags: JavaScript