Javascript parseInt Hilarity
What do you think this bit of javascript code returns?
parseInt(’09′)
My guess is it returns the integer 9 as parseInt() is meant to turn strings to integers. In actual fact it returns zero. Nothing. Nada. It took me a bit of digging to find out why. The reason it returns an unexpected result is one of those situations where the javascript parser attempts to be clever, but gets it wrong. You see parseInt actually has an optional second parameter, called ‘radix’. This specifies the base of the number system to use, and if you dont specify it, the javascript parser makes a ‘best guess’. The rules are:
- If the supplied value starts with ‘0x’ then the parser guesses it to be a hex value.
- If it starts with a zero, the parser guesses it is base 8, octal.
- Anything else is guessed as decimal.
So if we pass in ‘09′ without an optional radix, the parser thinks we are working in base 8, and as 9 doesnt exist in octal, it actually returns zero. Strange!
I’ve just knocked together a JavaScript pager for use in an application I’m working on and thought it may be of use to other people. I’ve therefore converted it to a jQuery plugin and released it under joint MIT and GPL licenses and it is entirely free for you to use or mess about with.
