7

If I use the code:

string = '010';
write = eval(string);
document.write(write)

I get 8 written on the page. Why? This happens even if 010 isn't a string.

phihag
  • 278,196
  • 72
  • 453
  • 469
Some Guy
  • 15,854
  • 10
  • 58
  • 67

3 Answers3

20

Because 010 is parsed as octal. Javascript treats a leading zero as indicating that the value is in base 8.

Similarly, 0x10 would give you 16, being parsed in hex.

If you want to parse a string using a specified base, use parseInt:

parseInt('010', 8); // returns 8.
parseInt('010',10); // returns 10.
parseInt('010',16); // returns 16.
developmentalinsanity
  • 6,109
  • 2
  • 22
  • 18
  • See http://www.javascripter.net/faq/octalsan.htm for more information. – KilZone Jul 16 '11 at 14:50
  • You can also override the default `parseInt()` behavior so that it no longer does this, as described here: http://codethink.no-ip.org/wordpress/archives/394 – aroth Jul 16 '11 at 14:58
4

Prefixing a number with an 0 means it's octal, i.e. base 8. Similar to prefixing with 0x for hexadecimal numbers (base 16).

Use the second argument of parseInt to force a base:

> parseInt('010')
8
> parseInt('010', 10)
10
phihag
  • 278,196
  • 72
  • 453
  • 469
  • +1 for providing a solution. Alternatively you can use unary `+`. – Felix Kling Jul 16 '11 at 14:51
  • Oh. Thanks a lot man. Interesting that the parseInt('010',10) trick won't work if the 010 isn't a string. – Some Guy Jul 16 '11 at 14:53
  • 4
    That's because if the 010 isn't a string, then it gets parsed as a numeric literal BEFORE being passed to parseInt as an argument. – developmentalinsanity Jul 16 '11 at 14:55
  • 2
    @The Awesome one. That's because `010` is already the number `8` when it's given to `parseInt`; `parseInt` can't distinguish whether its argument was `010`, `8`, `4+4`, or `parseInt("010")` – phihag Jul 16 '11 at 14:55
2

If you'd like to output the string 010 to the document, you can wrap the value in quotation marks:

var octal = eval('"010"');
typeof octal; // "string"

If you want to parse an integer or understand octals, read the other answers.

Simeon
  • 5,519
  • 3
  • 29
  • 51