Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is parseInt(021, 8) === 15? [duplicate]

Tags:

javascript

In reviewing parseInt(string, radix) in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

all 13 examples make perfect sense except for this one.

According to one example, parseInt(015, 10) will return 13. This makes sense assuming that numericals that begin with 0 are treated as an octal, regardless of the 10 that appears in the radix position.

So if the octal is specified as it is in the question header: parseInt(021, 8)

Then why wouldn't this be 17 (vs. 15 per the Mozilla documentation and in my tests in jsfiddle?

Any insight would be appreciated.

like image 418
James Lee Avatar asked May 01 '19 04:05

James Lee


2 Answers

This is because 0n is octal notation in javascript, just like Oxn is hex notation:

console.log(021 === 0x11 && 021 === 17);

So what you wrote got evaluated as parseInt(17, 8);

Then this 17 number gets coerced to the string "17" and the result is 15.

console.log(parseInt(17, 8))

Note that all this would not have happened in strict mode, where 0n notation has been deprecated:

(function(){
  "use strict";
  // Syntax Error
  console.log(parseInt(015, 8))
})();
like image 198
Kaiido Avatar answered Nov 06 '22 00:11

Kaiido


The first argument of parseInt should be a string. The same MDN link says:

The value to parse. If the string argument is not a string, then it is converted to a string (using the ToString abstract operation).

You can see that this works as expected:

console.log(parseInt("021", 8))

The problem in your tests is that you're using a number, not a string. When you use 021 as a number, as you already knows (when you said "numericals that begin with 0 are treated as an octal"), it gets converted to "17":

console.log(021.toString())

And that gives you the result you're seeing:

console.log(parseInt("17", 8))
like image 12
Gerardo Furtado Avatar answered Nov 06 '22 01:11

Gerardo Furtado