13

What's happening here and why?

document.write(0154); // === 108
Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
Shaz
  • 15,637
  • 3
  • 41
  • 59
  • You can also have it in hex: `document.write(0x154);` and see what you get. :-) – Shadow The GPT Wizard Feb 15 '11 at 13:28
  • [This silly behaviour is gone if you use strict javascript (that's new).](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/) Just put `"use strict";` at the top of the file/function. – Rudie May 13 '11 at 00:19

4 Answers4

26

Numbers that begin with 0 are considered octal (base-8) numbers.

base 8 [0154] = base 10 [108]

but if you had used a number that had an 8 or 9 you wouldn't have seen this problem since that neither 8 nor 9 is an octal digit.

typo.pl
  • 8,812
  • 2
  • 28
  • 29
  • Wow, can't believe I didn't even think of this. Thanks for the explanation! – Shaz Feb 15 '11 at 07:29
  • 4
    Whoever invented this behaviour should be locked away far from any computer. – GolezTrol Feb 15 '11 at 07:30
  • @GolezTrol Why? It's a widely accepted construct in a number of different contexts :) –  Feb 15 '11 at 07:41
  • 4
    @pst: Because the only *practical* effect of that behaviour in Javascript is causing programming errors. – Jean Hominal Feb 15 '11 at 09:09
  • 4
    It's widely accepted because someone invented it on a drunk sunday afternoon in 1872, and nobody remembers otherwise nowadays, but in a lot of contexts, leading zeros are just ignored. A 0o prefix or someting would make more sense, because you can see immediately that something is special about that number, even if you still need to look up what that 'o' stands for. – GolezTrol Feb 15 '11 at 11:05
12

0154 is octal. 1*64 + 5*8 + 4 = 108.

awm
  • 6,526
  • 25
  • 24
1

its octal number. octal=0154 & decimal is=108

Manish Trivedi
  • 3,481
  • 5
  • 23
  • 29
0

It is printing out the octal equivalent of what you wrote because it started with 0. Try 0001 (prints out 1), 0010 (prints out 8), 0011 (prints out 9)

corroded
  • 21,406
  • 19
  • 83
  • 132