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?

- 354
- 3
- 11
-
Best to `'use strict'` otherwise `0` in front of a number makes an octal. – elclanrs Jun 17 '16 at 17:42
-
Here's your answer: http://stackoverflow.com/questions/6718102/in-javascript-eval010-returns-8 – sohel101091 Jun 17 '16 at 17:43
5 Answers
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.

- 23,369
- 6
- 54
- 74
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
.

- 187,200
- 47
- 362
- 445
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.

- 1,220
- 8
- 20
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
.