JavaScript parseInt versus Leading Zeroes CodeUnit 24 AUG 2009

Coffee CupAnnoyingly, my JavaScript datePicker on one of our projects was throwing up peculiar values at certain page load times and to be honest, it simply didn’t make any sense to me. Certainly the values that I was passing to the date functionality was correct, for example Day: 24 Month: 08 and Year: 2009, but after passing these values to the new Date() constructor, I was simply getting rubbish back.

Until I had a closer look at what exactly I was doing to these values that I was passing on to the Date constructor that is…

Most of you will already know that the unary + operator and parseInt are not equivalent in terms of converting string values into integer values. + can convert strings to numbers yes, but it returns NaN if the element cannot be converted, while parseInt (which takes an optional second argument for the radix) does exactly the same thing, but also manages to extract leading numbers from a string if they are present. For example parseInt(“12x”) returns 12 while +”12x” returns NaN.

The other, more important difference I want to highlight is the different assumptions with regards to radix that these two functions make, particularly when it comes to dealing with leading zeroes. +”012″ returns 12 but parseInt(“012”) returns 10. Eh?

Well, what is happening here is that the leading zero is causing parseInt to treat the number as an octal number, causing the rather unexpected end result to be spit out, while + is automatically assuming a radix of 10.

(Of course, you could always use parseInt(“012”,10) to get around this).

So here’s a quick look then at the different results given by parseInt and + when dealing with leading zeroes then:

parseInt(’08’) -> 0
parseInt(‘010’) -> 8
+’08’ -> 8
+’010′ -> 10

Needless to say, this was exactly what was playing havoc with my split up date variables that I was throwing around and indeed, a quick switch from parseInt to + throughout my script sorted it out in an absolute jiffy! :)

Would have been nice to know about the + trick before I had released my datePicker out into the wild though!

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.