开发者

Syntax error, or no syntax error?

开发者 https://www.devze.com 2023-04-05 06:30 出处:网络
var zero = 0; zero.toString();// \'0\' --> fine 0.toString();// syntax er开发者_开发百科ror! 0..toString();// \'0\' --> fine
var zero = 0;
zero.toString();   // '0' --> fine
0.toString();      // syntax er开发者_开发百科ror!
0..toString();     // '0' --> fine

My conclusion: calling x.toString() doesn't only depend on the value of x, but also on the way x is presented.

Are there other such examples in JavaScript where I might get an unexpected syntax error due to presentation?


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 block
var o = {}; // empty object
({});       // empty object
0,{}        // empty object

{ foo: 'bar'} // block, `foo` label, 'bar' ExpressionStatement
var 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.:

function foo() {}.length;   // SyntaxError, `foo` is a function declaration
0,function foo() {}.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:

  • What does 1..something mean in JavaScript?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号