I understand that it is good syntax to use semicolons after all statements in Javascript, but does any one know why if/else statements do not require them after the curly braces?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
{
and}
begin and close a group of statementsBasically, an
if-else
must be followed by either a statement or a group of statements.if-else
followed by a statement:if-else
followed by group of statements:if-else
must end with a;
if it is followed by a single statement.if-else
does not end with a;
when followed by a group of statements because;
is used to end a single statement, and is not used for ending a group of statements.Because the curly braces themselves are termination characters.
The are tokens that enclose a compound statement block and are intrinsically terminated. It's like putting a period at the end of a sentence, it signals to the parser that the thought is complete.
While being completely ugly it is valid to wrap every statement in {} and omit the ;
The real answer is because many modern languages copied their syntax from C, which has this property. JavaScript is one of these languages.
C allows statement blocks
(which don't need terminating semicolons) to be used where statements can be used. So you can use statement blocks as then- and else- clauses, without the semicolons.
If you place a single statement in the then- or else- clause, you'll need to terminate it with a semicolon. Again, just as in C, with the extra JavaScript twist that ; is optional at the end of a line, if inserting it would not cause a syntax error.