views:

322

answers:

4

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?

+11  A: 

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.

cletus
Also after var foo = {"prop1":1,"prop2":2}; etc.
Robusto
@Robusto that's a variable assignment.
cletus
@cletus: It still needs a semicolon.
SLaks
@SLaks I know, it needs a semi-colon because it's a variable assignment (that was my point).
cletus
@Cletus: Just wanted to extend what you said, so OP didn't think you only meant function literals.
Robusto
Thank you very much for your answer, it was exactly what I was looking for. I often lose track of the smaller (albeit important) details when attempting to wrap my head around some of the more advanced concepts.
Rob
+4  A: 

It matters too when you intend to minify your code.

So I personally add one after every closing } brace.

alex
This is a very important point to note.
Rob
+4  A: 

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 = { };
SLaks
A: 

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.

kennebec