-4

Why does console.log(parseInt(0o22,8)) output 1?

Herr Derb
  • 4,977
  • 5
  • 34
  • 62
Minzer
  • 9

1 Answers1

10

0oNNN is ECMAScript 2015 syntax for literal octal numbers.

0o22 is 18 in decimal. parseInt needs a string, so this integer 18 is coerced to the decimal string '18' by parseInt. And since 8 is not a valid digit in base-8, parseInt bails out after the first digit and returns 1.

From MDN documentation for parseInt:

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.


See also: How do I work around JavaScript's parseInt octal behavior?