Now, come in the grouping operator, which return the result of evaluating an expression:

1

(function(){});

If we do it with named function:

1

2

functionfoo(){}

(foo);

or

1

(functionfoo(){});

But we haven’t done anything here, in another word, we haven’t invoked the function. We merely evaluate the function in three occasions. Function is object in JavaScript, when you’re evaluating an object, the result is still an object:

1

2

3

4

5

console.log(functionfoo(){}); // [Function: foo]

console.log(function(){}); // [Function]

functionbar(){}

console.log(bar); // [Function: bar]

console.log({}); // {}

Now, let’s apply function invocation, and do it the traditional way:

1

foo();

The function has been invoked, and it will return the result of the function.

Replace the identifier with function declaration:

1

functionfoo(){}();

However, this does not work. Because interpreter treats it as a function declaration, and ( will become an unexpected token. Function declaration cannot be invoked immediately. So, we need to make it an expression, by using the grouping operator:

1

(functionfoo(){})();

The function identifier is no longer necessary:

1

(function(){})();

Since grouping operator return the result of the expression, we can just drop it:

1

function(){}();

But this statement becomes a function declaration again, so we need to place the grouping operator around it:

1

(function(){}());

Okay, but what’s difference between:

1

2

(function(){}());

(function(){})();

There is no difference, they are both function expressions being invoked immediately. Function invocation can only be done via function expression. But first one is more align with foo(), the traditional way. According to the Code Convention for JavaScript Programming Language by Douglas Crockford:

When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

The invocation expression is function(){}(), and wrap it around parenthesis becomes (function(){}());.

Here we declare a function and name it “square”. But what is function expression?

var square = function(n){ return n * n; };

When you start a statement with keyword function, then the statement is function declaration, everything else is function expression.

Function expression can either be named or anonymous. The above is anonymous function, and here is a named one:

var square = functionsquare(n){ return n * n; };

There is a variable square and function name square, but they are not the same. The scopes are different. The function name square of the function expression can be only used inside the function, mainly for debugging purpose. Accessing from outside the function, will throw ReferenceError: