A JavaScript parseInt() gotcha

JavaScript No Comments »

Be careful of the JavaScript parseInt() function. It treats numbers that start with "0" as octal and "0x" as hexadecimal, which may not be what you want if the user entered a month of "09". Furthermore, parseInt() will not throw an exception if the parameter is bogus (as "09" is) — it will return NaN.

Therefore, consider using the optional radix option to parseInt() and always check for NaN with isNaN().

I have some thoughts about the use of exceptions vs. return values to indicate errors that I may get to in a future post.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in