2

I am studying JavaScript and I sometimes see something like this

function functionname()
{
   // Some statements
} () ;

What does () following } mean?

Thanks a lot, experts on Stack Overflow

  • The same as `()` after any other function. – SLaks Sep 16 '13 at 21:21
  • 2
    Well, the intention is probably to call the function immediately as the answers discuss. But, note that it's a SyntaxError in this snippet. A [function declaration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) as this appears to be cannot be followed immediately by `()`. However, a [function expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function) can (thus the `FE` in IIFE). This distinction is why there's often another set of parenthesis around the `function`, which force it to be an expression. – Jonathan Lonowski Sep 16 '13 at 21:27

3 Answers3

8

That is an IIFE (immediately invoked function expression). It is used to create a new scope. For example:

var x = 10;
(function() {
   var x = 5;
}());
alert(x); // still 10

All it does is define and call the function at the same time.


IIFEs are also used to "save" the value of a variable. For example, this code won't work:

for (var i = 0; i < buttons.length; i ++) {
    buttons[i].onclick = function() { alert(i) }
}

Every button will alert the last index when you click it, because after the loop is done i is buttons.length. To fix it, you would use an IIFE:

for (var i = 0; i < buttons.length; i ++) {
    buttons[i].onclick = (function(i) {
        return function() {
            alert(i)
        }
    })(i)
}

More info on IIFEs

tckmn
  • 57,719
  • 27
  • 114
  • 156
7

It calls the function.

var foo = function () { return 1; }();
alert(foo); // 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

There are lots of ways to define a function, when you do it like this ...

(function functionname(innerArguments){
   // Some statements;
})(outerArguments);

... the function is executed as soon as this piece of code is interpreted; its the same as:

function functionname(innerArguments){
   // Some statements;
};
functionname(outerArguments);
rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63
  • 1
    Note that these snippets aren't actually identical; the first one is interpreted as a function declaration and then a useless expression. Your first snippet defines the function but does not execute it. – tckmn Sep 16 '13 at 21:29