Here’s a fun one: let’s suppose you need to take a user-supplied date from an input field and turn it into a date object:
var date = $('#date').val(); //assuming yyyy-mm-dd for the demo var year = date.substr(0, 4); var month = date.substr(5, 2); var day = date.substr(8, 2); var newDate = new Date(year, parseInt(month) - 1, day, 0, 0, 0);
Simple enough, right?
Not so fast
That code won’t work in older browsers, and when I say old, yes I mean IE8.
Some of the time, anyway.
Here’s the trick: older versions of parseInt() work differently if there’s a leading 0, and the function will assume you’re using a non-base-10 numbering system. If it’s just 0 and a number, it’ll assume octal (base 8,) and if it starts with ‘0x’ it’ll assume it’s a hexadecimal number like 0xff.
The octal parsing has been deprecated in ECMAScript 5, but in the meantime, if you try to call parseInt with a number like, say, “08”, you’ll actually get 0 back, because octal only goes up to 7.
And that’s the kicker: Your date parsing code, if written as above, will work for 10 months of the year. Months 01-07 are valid octal numbers that happen to map to 1-7 in decimal. 08 and 09 are invalid and will result in 0, and 10, 11, and 12 don’t start with a 0 so they come back as you’d expect.
This means that depending on when you wrote the code, you might have time bombs lurking (and as I’m writing this in August, guess what I did this morning?)
The fix? Pass the second parameter to parseInt that specifies the radix (aka base): parseInt(“08”, 10) will work just fine in all browsers.