0
var zero = 0;
zero.toString();   // '0' --> fine
0.toString();      // syntax error!
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?

Randomblue
  • 112,777
  • 145
  • 353
  • 547
  • 1
    Another way is `(0).toString();` – epascarello Sep 17 '11 at 04:33
  • from what i know the `.` operator for objects, 0 just like that isn't an object yet, as @epascarello showed, (0) will transform it into an object, making the `.` operator available... the `..` does the same effect but you could also use a more explicit way like Number(0) – Dany Khalife Jun 24 '12 at 16:30

2 Answers2

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 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:

Community
  • 1
  • 1
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
0

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.

Community
  • 1
  • 1
Andy Ray
  • 30,372
  • 14
  • 101
  • 138