0

Why 2 + 10 = 12 and 2 + 010 = 10? I tried this on console of Google Chrome v 51.0 and IE 8 only to get the same results. Maybe this is feature of Javascript.
Somebody please help me understand the logic behind it and what possible good it can serve?

Narbhakshi
  • 354
  • 3
  • 11

5 Answers5

3

Its not binary, the 0 at the start makes it octal, and octal 010 == 8

https://en.wikipedia.org/wiki/Octal

emed
  • 747
  • 1
  • 9
  • 18
3

Sometime JavaScript treats numbers exactly as you specify them, other times it tries to 'interpret' the number.

In this case, JavaScript is interpreting the number.

The leading zero means that the number is octal -- base 8 -- where the digits go 0, 1, 2, 3, 4, 5, 6, 7.

So.. 010 (octal) == 8 (decimal)

2 + 010
2 + 8
10

If you are dealing with numbers from an outside source, you can use parseInt

2 + parseInt("010", 10);

Note: The ,10 is also important to force that number to be translated as base 10. In ES3 (and I believe 5) you may get different results without it, depending upon the browser.

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
2

0 before a number tells javascript to interpret the number as octal. So 10 in octal means 8 in decimal and 8 + 2 is 10.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
2

Numbers with leading 0 are considered as octal numbers. That is why 010 is interpreted as 8 hence you get 10 as sum of 2 + 010. This happens with python as well.

Nafiul Islam
  • 1,220
  • 8
  • 20
1

10 is equal to 8 in octal and the first zero tells javascript to interpret that as an octal number. So when 2 + 010 is executed, at first 010 is translated into 8 and then it is added to the 2 to give 10.