Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parseInt("010", 10); vs. parseInt(010, 10);

Tags:

javascript

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.

like image 376
AndrewJM Avatar asked Dec 01 '22 20:12

AndrewJM


2 Answers

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.

like image 167
p.s.w.g Avatar answered Dec 03 '22 08:12

p.s.w.g


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..

like image 44
Qantas 94 Heavy Avatar answered Dec 03 '22 08:12

Qantas 94 Heavy