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?
Curly brackets {} Curly brackets, also known as braces or curly braces, are rarely used in formal writing and are more common in other fields such as science, math, and computing. Some style guides will allow them to be used for one specific purpose: grouping together a set.
Parentheses are for separating citations or other asides from the body text. Brackets show changes within quoted material. Braces —sometimes known as curly brackets—are not typically used except in technical and mathematical writing.
Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.
In writing, curly brackets or braces are used to indicate that certain words and/or sentences should be looked at as a group.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With