Skip to content Skip to sidebar Skip to footer

ParseInt("010", 10); Vs. ParseInt(010, 10);

I'm confused about a particular result of parseInt. I thought I understood most of its quirks, but this one is unclear. parseInt('010', 10); // 10 parseInt(010, 10); // 8, but e

Solution 1:

Number literals beginning with zero are in octal, rather than decimal, so 010 is equal to 8, unless operating under strict mode.

It's important to note that the behavior of parseInt varies depending on what version of ECMAScript (JavaScript) your browser uses or if you're operating strict mode. See Octal Interpretations with No Radix for more detail.


Solution 2:

The number is being parsed before being passed to parseInt.

For example, it's similar to how this works:

var x = 010;
console.log(x); // 8
parseInt(x, 10); 

Since you're passing 8 in, of course you're going to get 8 back. Prepending a number with 0 will make it an octal literal, which is using a base of 8. You can either remove the leading 0 (having the leading 0 there doesn't really make sense in the first place), or (as you did in your question) pass it as a string.

Note that not all browsers do this, it is simply ones that are compatible with previous code that do this (it's not required), and implementations must not parse octal literals in ES5 strict mode. To see this in effect, compare the non-strict version:

(function ()
{   // not strict
    parseInt(010, 10);
})();

... which returns either 8 or 10 (depending on the implementation), with the strict version:

(function ()
{   "use strict";
    parseInt(010, 10);
})();

This will result in a SyntaxError: Octal literals are not allowed in strict mode..


Post a Comment for "ParseInt("010", 10); Vs. ParseInt(010, 10);"