Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do parenthesis after curly braces mean?

Tags:

javascript

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?

like image 309
jon Avatar asked Jun 21 '12 10:06

jon


People also ask

What are these {} brackets called?

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.

Are curly braces parentheses?

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.

What does {} mean in react?

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.

What is {} used for?

In writing, curly brackets or braces are used to indicate that certain words and/or sentences should be looked at as a group.


1 Answers

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?

like image 125
Felix Kling Avatar answered Oct 25 '22 06:10

Felix Kling