Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 00.0 cause a syntax error?

This is weird. This is what happens at the JavaScript console in Chrome (version 42.0.2311.135, 64-bit).

> 0 < 0 > 00 < 0 > 0.0 < 0 > 00.0 X Uncaught > SyntaxError: Unexpected number 

Firefox 37.0.2 does the same, although its error message is:

SyntaxError: missing ; before statement 

There's probably some technical explanation regarding the way JavaScript parses numbers, and perhaps it can only happen when tinkering at the console prompt, but it still seems wrong.

Why does it do that?

like image 704
Chris Dennis Avatar asked May 21 '15 08:05

Chris Dennis


People also ask

How do you fix a syntax error?

How to Fix It: If a syntax error appears, check to make sure that the parentheses are matched up correctly. If one end is missing or lined up incorrectly, then type in the correction and check to make sure that the code can be compiled. Keeping the code as organized as possible also helps.

What is syntax error in node JS?

The SyntaxError object represents an error when trying to interpret syntactically invalid code.

What is the best way to think about a syntax error?

If any person is not able to follow the rules and symbols of the language, then which words and symbols he spoke, that words and symbols come in a syntax error. In another word we can say that when any word reflects the property of language for which it is designed, then the concept of syntax error comes.


2 Answers

The expressions 0.0 and 00.0 are parsed differently.

  • 0.0 is parsed as a numeric literal 1
  • 00.0 is parsed as:
    • 00 – octal numeric literal 2
    • . – property accessor
    • 0 – identifier name

Your code throws syntax error because 0 is not a valid JavaScript identifier. The following example works since toString is a valid identifier:

00.toString 

1Section 7.8.3 – Leading 0 can be followed by decimal separator or ExponentPart
2Section B.1.1 – Leading 0 can be followed by OctalDigits

like image 79
Salman A Avatar answered Sep 22 '22 10:09

Salman A


00 is evaluated as an octal number and .0 is evaluated as accessing that number's property. But since integers are not allowed to be used as property accessors, the error is thrown.

You get the same error for any other object:

'string'.0 // Syntax error: unexpected number ({}).0 // Syntax error: unexpected number 

You can find related information about property accessors on MDN.

like image 24
Robert Rossmann Avatar answered Sep 19 '22 10:09

Robert Rossmann