ChatGPT解决这个技术问题 Extra ChatGPT

Why should I use a semicolon after every function in javascript?

I've seen different developers include semicolons after functions in javascript and some haven't. Which is best practice?

function weLikeSemiColons(arg) {
   // bunch of code
};

or

function unnecessary(arg) {
  // bunch of code
}

C
Cowdozer

Semicolons after function declarations are not necessary.

The grammar of a FunctionDeclaration is described in the specification as this:

function Identifier ( FormalParameterListopt ) { FunctionBody }

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.

FunctionDeclarations are evaluated before the code enters into execution, hoisting is a common word used to explain this behaviour.

The terms "function declaration" and "function statement" are often wrongly used interchangeably, because there is no function statement described in the ECMAScript Specification, however there are some implementations that include a function statement in their grammar, -notably Mozilla- but again this is non-standard.

However, semicolons are always recommended where you use FunctionExpressions. For example:

var myFn = function () {
  //...
};

(function () {
  //...
})();

If you omit the semicolon after the first function in the above example, you will get completely undesired results:

var myFn = function () {
  alert("Surprise!");
} // <-- No semicolon!

(function () {
  //...
})();

The first function will be executed immediately, because the parentheses surrounding the second one will be interpreted as the Arguments of a function call.

Recommended lectures:

Named function expressions demystified (great article)

Explain JavaScript’s encapsulated anonymous function syntax (more on FunctionDeclaration vs FunctionExpression)


Edited to clarify, that article talks about function expressions
Not entirely familiar with ECMA, but that is the standard I use as well. Good post. Most of the tuts I see online and code samples I DL use that standard, so I've just adapted to it.
Some of the confusion here may be influenced by lack of a good English word for "permitted because it will be ignored". We fall back on saying "optional", but that's misleading since it suggests that not including a semicolon after a declaration falls in the same category as not including a semicolon after a statement. The latter is optional in an entirely different sense: there it is because the parser will add the missing semicolon you omitted, while in this case, it is because the parser will ignore the semicolon you included. To put it another way: if one is optional, so are eight.
The link "Named function expressions demystified " links to a dead url now, the web archive has a copy here : web.archive.org/web/20100426173335/http://yura.thinkweb2.com/…
The last example is a great one. Omitting a semicolon in this case leads to extremely strange and hard-to-debug bugs. Wholeheartedly up-voting.
G
Gabe Moothart

I use them after function-as-variable declarations:

var f = function() { ... };

but not after classical-style definitions:

function f() {
    ...
}

NetBeans, as well as other IDEs like to see semi-colon after a function-as-variable such as this.animaton_fun = function () { ... };
But - for the questioner - why?
it helps during the build step. When an uglifier script sees a semicolon, it doesn't need to add a line break to the output file, if it doesn't, a line break will be generated and the file will be slightly larger.
J
Jonathan Arbely

JS Lint is de-facto convention, and it says no semicolon after function body. See the "Semicolon" section.


I've witnessed first hand a function that failed because of a lack of semicolon. I completely disagree that leaving it off is a convention. While 99.99% of the time it won't break, there are certain situations where I've noticed IE has been unable to interpet JavaScript without the semicolon.
My response only deals with function definitions such as in the question's two examples. In these cases, a terminating semicolon is not needed in any browser, in any situation. I guess you might be thinking of function expressions. They're a completely different matter, and not one that was addressed in the original question.
var myFunction = function(arg) { console.log(arg); } (function() { console.log('completely unrelated function'); return 'see what happens'; }());
@MillsJROSS I second David's response, and would be happy if you elaborate the failure you came across. Was it indeed a function expression or bug of IE?
J
Josh Stodola

Just stay consistent! They are not needed, but I personally use them because most minification techniques rely on the semi-colon (for instance, Packer).


r
regex

Really just depends on your preference. I like to end lines of code with semi colons because I'm used to Java, C++, C#, etc, so I use the same standards for coding in javascript.

I don't typically end function declarations in semi colons though, but that is just my preference.

The browsers will run it either way, but maybe some day they'll come up with some stricter standards governing this.

Example of code I would write:

function handleClickEvent(e)
{
     // comment
     var something = true;  // line of code
     if (something)  // code block
     {
        doSomething();  // function call
     }
}

lines should definitely be terminated with semicolons, tho. otherwise a minifier might break functionality entirely
@david: in that case the minifier is broken, surely?
Agreed. It is a natural way of coding for people (like me) coming from C/C++ backgrounds. It also makes the code more readable.
M
Mason

It's actually more than an issue of convention or consistency.

I'm fairly certain that not placing semicolons after every statement slows down the internal parser because it has to figure out where the end of the statement is. I wish I had some handy numbers for you to positively confirm that, but maybe you can google it yourself. :)

Also, when you are compressing or minifying code, a lack of semi-colons can lead to a minified version of your script that doesn't do what you wanted because all the white space goes away.


The question was geared towards if semicolons had to be after functions, not every statement. I agree that you should place semicolons after every statement, and I've seen other stackoverflow consensus saying the same.
Agreed, and failing to put semicolons after functions will result in that minification issue I mentioned. Good luck sir.
Upvote 'cause reinforcing the minification issue clarified my understanding
s
senera

When I minified my scripts I realized that I need to use semicolon for functions which starts with equals mark. if you define a function as var, yes you need to use semicolon.

need semicolon

var x = function(){};
var x = new function(){};
this.x = function(){};

no need semicolon

function x(){}

D
DilanTsasi

the semicolon after a function is not necessary using it or not, does not cause errors in your program. however, if you plan to minify your code, then using semicolons after functions is a good idea. say for example you have code like the one below

//file one
var one=1;
var two=2;
function tryOne(){}
function trytwo(){}

and

//file two
var one=1;
var two=2;
function tryOne(){};
function trytwo(){};

when you minify the both, you will get the following as output

Note that comments are just for ilustration

//file one
var one=1;var two=2;function tryOne(){}
function trytwo(){}

and

//file two
var one=1;var two=2;function tryOne(){};function trytwo(){};

S
Shaze

Edit: It doesn't matter with ECMAScript 2021 (ES2021) so please ignore the below statement.

It is a good practice to leave the semicolons ; after the end of function braces. They have been considered a best practice.

One advantage of always using them is if you want to minify your JavaScript.

As minifying the Javascript, helps to reduce the file size a bit.

But as for the best practise and answer above, not recommended to use it after a function tag.