3

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?

yegor256
  • 93,933
  • 106
  • 409
  • 558
  • Your code doesn't produce **any** SyntaxError, the Automatic Semicolon Insertion does **not** affect an `AssignmentExpression`, check [this example](http://jsbin.com/ukimi/edit). – Christian C. Salvadó Jul 04 '10 at 14:19

1 Answers1

2

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

var x = ;
Fabien Ménager
  • 139,874
  • 3
  • 38
  • 60
  • For this reason, it's recommended to always use the second form. – Skilldrick Jul 04 '10 at 11:25
  • Thanks, this is exactly what it is – yegor256 Jul 04 '10 at 11:35
  • 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 – gblazex Jul 04 '10 at 11:59
  • 1
    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). – Christian C. Salvadó Jul 04 '10 at 14:15
  • 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 Jul 10 '10 at 20:45