Javascript 0 in beginning of number

Gor picture Gor · Jan 27, 2016 · Viewed 11k times · Source

I just want to understand js logic with 0-s in beginning of number. For example

var x = 09.3
// here x == 9.3
// other example
09.3 == 9.3
// returns true

// but check this one
var x = 02.5
// Uncaught SyntaxError: Unexpected number
// or this one
02.5 == 2.5 
// same error here

Can anyone explain, how it works, why in first example it works, and ignores leading zeros, but in second example it gives me a SyntaxError

Thank you

Answer

Pointy picture Pointy · Jan 27, 2016

Leading 0 on a numerical literal indicates that an octal integer is the intention, unless the second digit is 8 or 9. In that case, the leading 0 is ignored.

Because octal numeric literals must be integers, 02.5 is erroneous.

This behavior was logged as a bug in Firefox in 2014, but because there's so much JavaScript code in the world and so much of it (probably inadvertently) relies on 09.3 not being a syntax error, the bug was marked "WONTFIX".

As pointed out in a comment below, in "strict" mode octal constants are disallowed entirely.