3

I hunted down a bothersome JavaScript error where I was passing one argument, but when it was received, it was something completely different. I fixed it, but would like to know what was happening for future reference.

What I should have passed as an argument is '0616' (with quotes). What I actually passed was 0616 (without the quotes).

So, when it was received, some kind of implicit numeric conversion took place, and it was received as 398. I understand implicit and explicit conversion, but WHAT was happening to turn 0616 into 398. The leading zero seems to have something to do with it because other values that I passed that were non-zero in the most significant digit survived just fine. It's only those that begin with zero?

But what relation is there between 398 and '0616' ?

Any ideas?

Οurous
  • 348
  • 6
  • 17
KWallace
  • 1,570
  • 1
  • 15
  • 25

3 Answers3

5

Ahh the magical world of javascript!!

Any numeric literal that starts with a 0 is treated as an octal number.

A hacky workaround is

parseInt('0616', 10)
Michael Voznesensky
  • 1,612
  • 12
  • 15
  • Sorry for my previous comment, but I think `parseInt('0616', 10)` would be safer, in case he still have to support some old browsers, which have interpretation for octal. – Leo Dec 04 '14 at 01:30
3

0616 is the old octal number format. In new spec it should be 0o616, however the old format is still supported by browsers.

See this wiki page:

prefix 0o was introduced to .... and it is intended to be supported by ECMAScript 6 (the prefix 0 has been discouraged in ECMAScript 3 and dropped in ECMAScript 5).

Leo
  • 13,428
  • 5
  • 43
  • 61
2

the reason is that the leading zero is javascript notation for base octal, e.g. 010 = 8. The notation for hexadecimal is a leading 0x, e.g. 0x10 = 16

alzclarke
  • 1,725
  • 2
  • 17
  • 20