Do we need a semicolon after function declaration?

Semicolons and function declarations:

function test(o) {
    // body
} // semicolon no

var test = function (o) {
    // body
}; // semicolon yes

See JSLint for formatting code questions.


No.

You don't need semicolons when defining a function like that.

However, if you define a function like this:

var test = function (o) {
}

It's not strictly necessary, but you may want to use them, especially if you put the function on one line.

The first way defines a function, but the second way assigns a function to a variable, and thus is a statement. Most statements are semicolon delimited. Defining functions could be considered a common counterexample, as not many people do use them.


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.


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.

Tags:

Javascript