Skip to content Skip to sidebar Skip to footer

Syntax Error, Or No Syntax Error?

var zero = 0; zero.toString(); // '0' --> fine 0.toString(); // syntax error! 0..toString(); // '0' --> fine My conclusion: calling x.toString() doesn't only depe

Solution 1:

Well, there are other cases where the context of where symbols appear affects how they behave, for example, statement Block's vs Object Literals:

{}          // empty blockvar o = {}; // empty object
({});       // empty object0,{}        // empty object

{ foo: 'bar'} // block, `foo` label, 'bar' ExpressionStatementvar o = { foo: 'bar'}; // object literal, declaring a `foo` property// whose value is 'bar'

They look exactly the same, but blocks are evaluates in "statement context", object literals are evaluated in expression context.

Also, Function Declarations vs. Function Statements, e.g.:

functionfoo() {}.length;   // SyntaxError, `foo` is a function declaration0,functionfoo() {}.length; // 0, `foo` is a function expression
(function foo {}).length;   // 0

The example you post, relates to the way the grammar of Numeric literals are defined, the decimal part after the dot is actually optional, for example:

var n = 0.;

Is a valid Numeric literal, that's why, accessing 0.toString gives you a SyntaxError, the interpreter would expect the decimal part, instead the s character.

See also:

Solution 2:

The value of a variable doesn't matter, but the way it is "presented" might make it valid or invalid syntax. See this highly upvoted answer. It's just an oddity of the EcmaScript syntax definition.

Post a Comment for "Syntax Error, Or No Syntax Error?"