[JavaScript] parseInt() Quirks

Here’s a subtle little feature of JavaScript’s ‘parseInt()‘ function that I recently stumbled across. The radix used in the parse will default to 8 (octal) if the string you are parsing includes a leading zero. For instance:

parseInt("07");

…will return 7, as expected, but:

parseInt("08");

…will return 0, because 8 is not a valid digit in a base-8 number system. Technically the ‘parseInt()‘ function is behaving to spec in each instance, but this can lead to some very confusing errors if you’re not expecting this behavior. A simple fix exists, however:

parseInt("08", 10);

…will return 8, as expected. Explicitly specifying a radix of 10 overrides the function’s quirky default behavior (which as near as I can tell is a relic carried over from C and Java, which both use a leading zero to specify octal literals…why they didn’t opt for something more clear, like suffixing the value with ‘o’, I cannot say). Here is a quick example comparing the two.

An alternate fix to this issue is to simply override the parseInt() function, like so:

			window._oldParseInt = window.parseInt;
			window.parseInt = function(str, rad) {
				if (! rad) {
					return _oldParseInt(str, 10);
				}
				return _oldParseInt(str, rad);
			};

This will change the behavior of ‘parseInt()‘ to match that of Java’s ‘Integer.parseInt()‘ function (the radix used is always 10 unless the developer explicitly overrides it), which provides for a much more consistent and predictable experience.

Note, however, that this quirky behavior is a documented (albeit deprecated) feature of the ‘parseInt()‘ function; though it is certainly not something that one intuitively expects. Interestingly enough, its deprecation means that browser implementors are free to drop support for this confusing default at any time. However, complete removal of this feature seems unlikely to happen, as doing so would break existing websites that rely upon it.

Perhaps a reasonable middle ground would be to preserve the default behavior when the string being parsed includes only valid base-8 numbers, and default to base-10 if any other numbers are present in the string. That would help in simple cases like the ones shown above, but still may generate confusing output for inputs like “0107″ and the like.

Really the problem here is one of a poorly designed spec. Instead of picking the most common usage mode and making that the default, like Java does in its ‘Integer.parseInt()‘ function, someone decided to try to infer the desired usage mode based upon the input parameter. And that may be fine when there are no ambiguous mappings from input parameters to usage modes, but that is not the case here. Whenever such ambiguous mappings exist, it is always better to just make the most common usage mode the default, and let the developer override it if they want something different.

Otherwise you produce code that can yield confusing and unexpected behavior, and you dig everyone else into a hole where they must continue both supporting and working around your poor design decision.

This entry was posted in coding, javascript and tagged , . Bookmark the permalink.

3 Responses to [JavaScript] parseInt() Quirks

  1. MoliOwehoolve says:

    Hi, i just wanted to come here to inform you of a very inexpensive service that posts comments like this on millions of WordPress blogs. Why you might ask, well you might want to sell something and target webmasters or simply just improve the quantity of backlinks your website has that will improve your Google rankins which will then bring your website more traffic and cash.

  2. UnjuppyOvanny says:

    Hey. I want to share a really cool SEO product. I just made a YouTube video reviewing it. I really think you should check it out if you have a website or want to start earning serious money online. It comes with a 14 day free trail which is the best part! You don’t have to buy anything! SENuke

  3. bt says:

    Great site. Keep doing.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>