tags:

views:

44

answers:

1

My javascript code that produces a syntax error:

var x =
{
  a: 123
};

The same code without an error:

var x = {
  a: 123
};

What the heck?

+2  A: 

Javascript adds implicit ";" at the end of lines sometimes, I suppose this is what happens, and results in

var x = ;
Fabien Ménager
For this reason, it's recommended to always use the second form.
Skilldrick
Thanks, this is exactly what it is
Vincenzo
it is one of the gotchas in javascript: http://stackoverflow.com/questions/3154215/what-are-the-most-common-causes-of-errors-in-javascript-and-how-to-fix-them/3154285#3154285
galambalazs
That's not true. The variable statement is affected by the *Automatic Semicolon Insertion*, but the example that the OP posts, will *not cause any syntax error*, the `AssignmentExpression` will be evaluated *without problems*, check this question for the specific [rules of ASI](http://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion/) and [this example](http://jsbin.com/ukimi/edit).
CMS
I was also surprised by the error the OP had, so what could be the problem ? Thank you CMS for the correction.
Fabien Ménager