Your interpreter thinks you're going to make an object literal, like { var: x }
would be. { var x; }
is not a good object syntax, as there should be a colon after the indentifier var
, not x
. Thus, SyntaxError
.
You can force the parser to think it's a code block after all by prepending any of the hints that it is actually a code block:
label: { var x; }
if (true) { var x; }
do { var x; } while (false);
EDIT: Also, note that there is no good reason to do this. If you are not using a code block as a statement group for a flow control statement, or as a target for a label, it is utterly useless (and a potential source of hard-to-track bugs, as you found).
In other languages, you might be controlling the scope of variables (I expect you wanted to make sure x
was not visible outside the block?). In JavaScript, only functions have scope. Thus, to isolate variables from the surrounding environment, you need a function:
{
var x1;
};
x1; // undefined
(function() {
var x2;
})();
x2; // Uncaught ReferenceError: x is not defined