Possible Duplicate:
JavaScript: When should I use a semicolon after curly braces?
Someone added semicolon after function declaration, but someone not. Is this a good practice to add semicolon after function declaration?
function test(o) { } function test(o) { };
Semicolons after function declarations are not necessary. There's no semicolon grammatically required, but might wonder why? Semicolons serve to separate statements from each other, and a FunctionDeclaration is not a statement.
They are only mandatory, if you want write multiple statements in the same line. Some Python programmers write semicolons at the end of the line, because they are so used to it from other languages. Thus, there is no need for the semicolon after num = 8 , and you should avoid it, because it's unusual.
while' loop syntax needs a semicolon at the end. Whereas for and while loop do not need a semi-colon terminator at end.
JavaScript Learn JavaScript Quick Course BeginnersAdding semicolons after every function is optional. To avoid undesirable results, while using functions expressions, use a semicolon.
A function declaration does not need (and should not have) a semicolon following it:
function test(o) { }
However, if you write a function as an expression, like the variable initializer below, then the statement should be terminated with a semicolon, just like any other statement would be:
var a = function test(o) { };
See more about constructor vs declaration(statement) vs expression.
What's actually happening there is you're adding an empty statement after the function.
function test (o) { return o; };
could be seen as being similar to:
var test = 0;;
That second semicolon isn't an error per-se. The browser treats it like a statement where absolutely nothing happened.
There are two things to keep in mind, here.
This applies ONLY to function-declarations and control-blocks (for/if/while/switch/etc).
Function-declarations should be defined at the bottom of your scope, so you don't run into problems like this:
function test () {} (function (window, document, undefined) { /* do stuff */ }(window, document));
Because the browser will assume that you mean function test() {}(/*return value of closure*/);
Which is an error. A very bad and nasty error which is very easy to overlook.
But that's okay, because function-declarations can go under return statements and still work just fine.
So even if you wanted to go:
function doStuff () { return (function () { /*process stuff*/ test(); }()); function test () {} }
That's going to work just peachy.
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