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?
You use a semi-colon after a statement. This is a statement:
var foo = function() {
alert("bar");
};
because it is a variable assignment (ie 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.
It matters too when you intend to minify your code.
So I personally add one after every closing }
brace.
You never need to; you always can (except before else
and while
).
Explanation:
Unfortunately, Javascript semicolons are optional.
Therefore, you never need to add a semicolon.
It is (very) good practice to terminate every statement with a semicolon.
The only statements that end with a }
are statements ending with a JSON literal or function expression.
Therefore, best practice is to put semicolons after the following two braces (only):
var myFunc = function() { };
var myobject = { };
Semicolons go at the end of lines that do not end in a curly brace or to separate statements on the same line. It does no harm to use them after a closing brace, or to wear suspenders and a belt, but it does look a little nerdy.