Javascript is weird

Someone should kindly explain why console.log(0725) doesn’t log the right number.

What you have here is a number in the octal system (or base-8). Everybody uses the decimal system (or base-10) in everyday life. Whereas base-10 has 0 to 9, base-8 is a number system with only 0 to 7. In the base-8 system, each digit represents a power of 8. The 5 in your example is just 5, the 2 is really 2 * 8 = 16, and the 7 is really 7 * 8 * 8 = 448. Adding these together you’ll get 469, which is what’s printed in the console.

In js (and IIRC in some other languages) when you prepend a number value with 0, you’re writing it in the octal system.

2 Likes

Pretty sure it was C that introduced the leading 0 thing. Probably BCPL before that but no one cares (or should) about BCPL. That JS copied it is … unfortunate. Octal is good for expressing file permissions in Unix, and that’s about it.

Except decimal numeric system, JavaScript additionally supports 3 more:

  • hexadecimal
  • octal
  • binary

The correct literal notation is as follows:

const dec = 15; // 15
const hex = 0xf; // 15
const oct = 0o17; // 15
const bin = 0b1111; // 15

The fact that 017 also reads by parser as octal is a very bad behavior, but as you know the philosophy of JS is total backward compatibility, so this is what we have to live with :slight_smile:

To demonstrate, why it’s bad:

const oct = 017; // 15
const dec = 019; // 19

Thanks for the explanation.
This messed up my code big time.

Just curious, was there a reason you needed to have a leading zero?

I took the substr of a string and that was the value returned. When I checked my DB, I noticed that the value saved was different from the value I was expecting.

How would then parser distinguish between decimal and octal?