Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use a semicolon after curly braces?

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?

like image 327
Rob Gibbons Avatar asked Apr 27 '10 00:04

Rob Gibbons


People also ask

Do you need semicolon after curly braces JavaScript?

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

Can you put a semicolon after a bracket?

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.

What loops need a semi colon after?

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.

Do you need a semicolon after return?

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.


1 Answers

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.

like image 148
cletus Avatar answered Oct 02 '22 20:10

cletus