0

there are some behaviors I don't understand in Javascript :

  1. Why console.log(011666) logged 5046 ?
  2. Why typeof typeof 500 logged string ?
  • 2
    A number starting with `0` is interpreted as octal number. `typeof 500` returns a string. The type of a string is `'string'` –  Jun 12 '21 at 13:55
  • This thing with leading zero making number octal is luckily being slowly fixed. ES6 introduced octals prefixed with `0o` (zero followed by 'o' for 'octal'). I'm happy to see JavaScript's idiocracy being addressed. – Robo Robok Jun 12 '21 at 14:00
  • @RoboRobok That's not just JavaScript. Multiple languages have this. It's at least C, C++ and PHP and probably more. –  Jun 12 '21 at 14:01
  • Don't know about other languages, but it's just dumb. Why octal and not binary, for example? Or just decimal? It's not clear what it does when you read it without knowing this random fact that it's actually octal. – Robo Robok Jun 12 '21 at 14:03
  • Duplicate of [Why JavaScript treats a number as octal if it has a leading zero](/q/37003770/4642212) and [duplicate](//google.com/search?q=site%3Astackoverflow.com+js+typeof+typeof+is+string) of [typeof typeof x returns string and not object since type of null is object](/q/43171010/4642212). – Sebastian Simon Jun 12 '21 at 14:05
  • @RoboRobok I'd say JavaScript has more serious problems than a very common number convention, e.g. `{} + {} === NaN` –  Jun 12 '21 at 14:06
  • @jabaa of course, I completely agree that these other problems are more serious. Nevertheless, my opinion is that 0-prefixed octals are stupid too. They are begging for hard-to-find bugs. – Robo Robok Jun 12 '21 at 14:07
  • @jabaa `({} + {})` is `"[object Object][object Object]"`. Are you referring to the object–block syntax ambiguity itself? – Sebastian Simon Jun 12 '21 at 14:08
  • @SebastianSimon I was referring to https://www.destroyallsoftware.com/talks/wat without checking it but obviously I have misunderstood something. –  Jun 12 '21 at 14:11
  • @SebastianSimon `{} + {} === NaN` in the Firefox dev tools console. –  Jun 12 '21 at 14:16
  • 1
    @jabaa That’s only because it’s interpreted as `{}; +{};` which is an empty block statement, then a unary plus applied to an object (which is coerced to a primitive, but that’s `"[object Object]"`, which isn’t a numeric string, so the result is `NaN`). All explained in [What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?](/q/9032856/4642212). Also, `{} + {} === NaN` is impossible… you mean `isNaN(+{})`, which isn’t really that mysterious. – Sebastian Simon Jun 12 '21 at 14:21
  • @SebastianSimon Thanks. Good to learn about reasons for this behavior. –  Jun 12 '21 at 14:23

1 Answers1

5
  1. A number starting with 0 is interpreted as octal number. A simpler example:

console.log(010);
  1. typeof 500 returns a string 'number'. The type of a string 'number' is 'string'.

console.log(typeof 500);
console.log(typeof 'number');