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?
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.
Control statements ( if , do , while , switch , etc.) do not need a semicolon after them, except for do ...
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.
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.
{
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 (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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With