Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

Why does 018 - 015 equal 5 in JavaScript?

Do you know what will be the output of this code?

JavaScript
console.log(018 - 015);
Show answer and explanation

This will actually result in 5 but this is pretty strange, isn’t it?

Please note, that this example will only work in lax mode, and not in strict mode, and we will come to the explanation soon enough.

In earlier versions of JavaScript, a leading 0 on a number marked an octal number.

Octal numbers are numbers with a base of 8 (instead 10 like with decimal numbers).

This means that numbers from 0 to 7 are valid digits.

In our case, 018 can’t actually be an octal number, can it?

Well it can’t and the runtime knows this, which is why it treats 018 as 18 although the right side contains a perfectly valid octal number 015 which is 13 in decimal.

And the runtime will perform the calculation exactly like this, which results in:

18 - 13 -> 5
Take the full quiz Next question →

More Numbers questions

  1. Why is typeof NaN "number" in JavaScript?
  2. Why is 0.1 + 0.2 == 0.3 false in JavaScript?
  3. Why is Math.max() < Math.min() true?
  4. What is -7 % 3 in JavaScript?
  5. Why does indexOf not find NaN but includes does?

Related topics