Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are semicolons not used after if/else statements?

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?

like image 250
Ronathan Avatar asked Jun 11 '13 03:06

Ronathan


People also ask

Can we use semicolon after else?

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.

Which statement must not end with semicolon?

Control statements ( if , do , while , switch , etc.) do not need a semicolon after them, except for do ...

What happens if you put a semicolon after an if statement Java?

The semi-colon in the if indicates the termination of the if condition as in java ; is treated as the end of a statement, so the statement after if gets executed.

Do you need semicolons after IF statements in JavaScript?

Semicolons come after if or else in JavaScript. They would belong after statements inside if or else blocks but they are technically optional. if blocks start with if and contain a statement block which is either one expression or { + one or more expressions + } . else blocks work the same way.


1 Answers

  • 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.

like image 200
invisal Avatar answered Oct 13 '22 01:10

invisal