Many times I've seen a semicolon used after a function declaration, or after the anonymous "return" function of a Module Pattern script. When is it appropriate to use a semicolon after curly braces?
Avoid! You shouldn't put a semicolon after a closing curly bracket } . The only exceptions are assignment statements, such as var obj = {}; , see above. It won't harm to put a semicolon after the { } of an if statement (it will be ignored, and you might see a warning that it's unnecessary).
Sometimes the parenthetical material is part of a longer sentence part that will be set off by a comma, colon, or semicolon. These pieces of punctuation always come after the parenthetical material, never before it or inside the parentheses.
I am just curious as to why a 'do ... while' loop syntax needs a semicolon at the end. Whereas for and while loop do not need a semi-colon terminator at end.
All developers writing JavaScript should understand automatic semicolon insertion as it relates to return statements. JS uses automatic semicolon insertion. This means JS engines will execute code and insert any semicolons where it sees fit. One of those spots is after a return statement.
You use a semicolon after a statement. This is a statement:
var foo = function() { alert("bar"); };
because it is a variable assignment (i.e. creating and assigning an anonymous function to a variable).
The two things that spring to mind that aren't statements are function declarations:
function foo() { alert("bar"); }
and blocks:
{ alert("foo"); }
Note: that same block construct without semi-colon also applies to for
, do
and while
loops.
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