I type the following example in the Google Chrome console (and I get an interesting result):

for (num = 050; num <= 100; num = num + 1) { console.log(num); } 

For some reason, printing starts from 40. If you enter num = 50 instead, then from 50. What is the difference between these values ​​for JavaScript, and why does the cycle start from 40 in the first case?

  • four
    because numbers starting with zero are considered octal if they have no numbers greater than 7 - Grundy
  • @Grundy: Why not as an answer? - VladD
  • @VladD, well, somehow one line of everything :-) and I wanted to find some kind of link confirming - Grundy
  • And 08 seems to be a mistake, isn't it? - VladD
  • @Grundy: developer.mozilla.org/ru/docs/Web/JavaScript/Guide/… ? (hmm, no scrolling) - VladD

2 answers 2

Numbers starting with zero are considered octal if they do not contain numbers greater than 7. Reference for help

Grammar can be viewed in the specification: 11.8.3 Numeric Literals

  • Thank you, I hope not a stupid question was)) - Zhenya Vedenin
  • one
    @ ZhenyaVedenin, in fact, a normal question for not quite obvious features - Grundy
  • * there are no numbers greater than 7 - Sergiks
  • @Sergiks, and I was so too lazy to correct that I was hoping no one would notice :-D - Grundy
  • one
    @Regent, but I missed it :-) thanks - Grundy

JavaScript defines an integer octal literal as follows.

 OctalIntegerLiteral :: 0o OctalDigits 0O OctalDigits OctalDigits :: OctalDigit OctalDigits OctalDigit OctalDigit :: one of 0 1 2 3 4 5 6 7 

As you can see, literals starting with 0, followed by a lowercase o or uppercase O , are integer octal literals.

The problem is that, for example, I could not use this literal in IE 11 regardless of the mode selected ("USE STRICT"). :) While in FireFox 42, this literal is successfully processed.

Also in JavaScript is defined the so-called LegacyOctalIntegerLiteral

 LegacyOctalIntegerLiteral :: 0 OctalDigit LegacyOctalIntegerLiteral OctalDigit 

In your case, this literal is used.

In the EcmaScript specification (6th edition) there is a remark that

If you’re looking at what you’re looking for in B.1.1, you’ll find out what you’re looking for.

However, as usual, each browser goes its own way. :)

  • not the first character O , but 0o or 0O , that is, this: 0o10 octal number, but this o10 can be a regular variable, and if it is not declared, it will be Uncaught ReferenceError: o10 is not defined (...) - Grundy
  • @Grundy I was distracted and looked the wrong way when I wrote the text. :) - Vlad from Moscow
  • one
    and where is the way the grammar looked? :) - Grundy
  • @Grundy I watch ECMA-262. I was distracted earlier because for some reason in IE 11 the octal literal is not perceived regardless of the selected mode. :) - Vlad from Moscow
  • Yeah, I added a link to the specification to my answer, by the way, as I understood in the Edge they repaired and this literal works fine :) - Grundy