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?
In your example, you simply have two statements and it is equivalent to:
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:
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:
This is a named function expression. The result of the expression (
(function ....)) is a function reference, and(0)executes the function, passing0as argument.The position of the parenthesis could also be:
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?