| Subscribe via RSS

Javascript parseInt Hilarity

June 3rd, 2009 | Comments Off | Posted in JavaScript

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!

  • Cloud

    Ajax AmpliFeeder ASP.NET Blabnote C# Cloud Design EntityFramework Framework JavaScript JQuery LINQ Live Mesh MicroBlog Mix07 Mobile Productivity Rails Remix08 SDS Silverlight2 SQL SSDS TDD Telecommunications Uncategorized VOIP WCF Web 2.0 Webcast

  • @jonpauldavies