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

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:

Leave a Comment