What do parenthesis after curly braces mean?

javascript

Solution

In your example, you simply have two statements and it is equivalent to:

function foo(bar){
  return bar;
}
0;

This is not a self-invoking function. The first statement is a function declaration, the second statement is simply the number literal `0`, which does not do anything. The parenthesis don't execute the function, they are the grouping operator.

How can we prove this? Try:

function foo(bar){
  return "bar";
}(0);

and tell me what the output is.

It would be a self-invoking function, if we had a function expression. For that you can use the grouping operator to force it being evaluated as expression.

For example:

(function foo(bar){
  return bar;
})(0);

This is a named function expression. The result of the expression (`(function ....)`) is a function reference, and `(0)` executes the function, passing `0` as argument.

The position of the parenthesis could also be:

(function foo(bar){
  return bar;
}(0));

Maybe this is what you have seen.

This technique was already extensively discussed here: What is the purpose of a self executing function in javascript?

Problem

I have seen Javascript code that uses parenthesis immediately after a function's closing curly brace, I can't understand what they're used for. Example: ``` function foo(bar){ return bar; }(0); ``` What does `(0)` do? What is this called? When should you use this technique?

Original source

Related problems