Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript 0 in beginning of number

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

like image 704
Gor Avatar asked Jan 27 '16 21:01

Gor


People also ask

How do you put a zero at the beginning of a string?

Use the padStart() method to add leading zeros to a string. The method allows us to pad the current string with zeros to a specified target length and returns the result.

Is 0 a number in JavaScript?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

How do you add leading zeros to numbers or text with uneven lengths JS?

Use the padStart() method to pad the string with leading zeros. The padstart() method will add leading zeros to the start of the string until it reaches the specified target length.


2 Answers

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.

like image 190
Pointy Avatar answered Oct 08 '22 01:10

Pointy


A leading zero indicates an octal (base 8) number (as opposed to a decimal - base 10 - number).

A leading 0x indicates a hexadecimal number, and a leading 0b a binary number.

Therefore 09.3 defaults to decimal because the digit '9' doesn't exist in octal notation.

Edit (credit Evan Trimboli, below): 02.5 throws an exception because octal literals must be integers.

like image 34
andydavies Avatar answered Oct 08 '22 02:10

andydavies