The formal syntax for if else
is something like:
if
statement else
statement
The generic "statement" there can be something like a simple assignment expression, a single function call, or a block of one or more statements enclosed in { }
. Thus, the { }
are not part of the syntactic structure of the if
statement. They're part of the general and often-used compound statement. (JavaScript may formally call that something else; it's a common thing however and the name isn't so important. edit A comment notes that it's formally a "block statement", but I think "compound" is more descriptive so I'll leave it in.) A brace-enclosed compound statement contains any number of other statements, but from the outside it comprises just one statement.
The else
part of the if
statement is optional, so
if
statement
is fine too.
Thus, in your examples:
if (boo)
console.log(a);
The console.log(a);
is the single statement. In the second example:
var boo = true;
if(boo == true){
console.log("a");
}else{
console.log("not true");
}
there is an else
clause, and both the if
and the else
have compound statements playing the role of the single statement in the formal syntax.
As to exactly how the parser understands that, well, that's a big topic. Suffice to say that programming languages are designed to be as unambiguous as possible, so that the code to parse the raw text of a program can be as simple as possible. Of course, as with anything, no such design is perfect, and in particular JavaScript has syntax features that are surprisingly hard to parse. What we're talking about here, however, isn't one of those. The whole purpose of the { }
wrapper around a compound statement is to give the parser a clear signal: here comes a compound statement.