According to this, JavaScript will insert a semicolon if:
When the program contains a token that is not allowed by the formal grammar, then a semicolon is inserted if (a) there is a line break at that point, or (b) the unexpected token was a closing brace. (emphasis mine)
The classic example is
return // <--- semicolon inserted there
{
id: 12
};
Which leads me to believe that a free standing {
is not valid. Yet the following (pointless) code alerts 2, without error
function foo() {
var x = 1;
{
var y = 2; //yes, I know y has the same scope as x
} //and that this is therefore pointless
alert(y);
}
Why is the opening brace treated as an invalid token in the first code, which leads JavaScript to insert a semicolon, but the opening brace is not treated as invalid in the second—as evidenced by the fact that there is no error.
Clearly one of my assumptions is wrong, and I was hoping someone could help me understand which.