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 expecting 10
In the second example I specified the correct radix. What's the reason for the unexpected result?
Solution
The problem is with octal literal. When a number is prepended with 0, it's seen an as octal literal.
If you execute
console(010); // 8
in non-script mode, you will get 8. The reason that parseInt is having what I thought was strange behavior was because I was essentially executing
parseInt(8, 10); // 8
and expecting 10.
ParseInt never saw 010, only 8. Thanks to everyone for helping out.
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.
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.
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With