简体   繁体   中英

Why are semicolons not used after if/else statements?

我知道在 Javascript 中的所有语句之后使用分号是一种很好的语法,但是有人知道为什么 if/else 语句在大括号之后不需要它们吗?

  • Semicolon is used to end ONE statement
  • { and } begin and close a group of statements

Basically, an if-else must be followed by either a statement or a group of statements.

if-else followed by a statement:

if (condition) statement;
if (condition); // followed by a statement (an empty statement)

if-else followed by group of statements:

if (condition) {
   statement;
   statement;
}

if (condition) {
   // followed by a group of statements of zero length
}

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.

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.

Because the curly braces themselves are termination characters.

They 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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM