2

I consider myself a pretty strong javascript coder and am familiar with most all of the javascript syntax. But have been puzzled by the following syntax:

function() {
    return function() {

    }
} ();

Can someone explain what the parenthesis at the end is supposed to be used for?

tonejac
  • 1,083
  • 3
  • 18
  • 32

2 Answers2

3

So, the expression:

(function() {
    return function() {

    }
})

Evaluates to a function (without a name in this case) that returns some other function.

Adding ():

(function() {
    return function() {

    }
})();

Would simply call that function.

Another way to write this would be:

var foo = function() {
        return function() {

        }
    };

foo();
Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
  • So it's just a different way to write the same pattern as your third example? Okay, I get it. Thanks. Good explanation. – tonejac Mar 05 '14 at 19:44
  • @tonejac - Correct. It's a bit more compact, because it doesn't use a variable to reference the function you just created. It just declares it, then calls it immediately. – Mike Christensen Mar 05 '14 at 19:46
  • Okay, connections are now firing in my brain, that makes total sense now! Thx. – tonejac Mar 05 '14 at 19:48
  • 1
    It's called an immediately-invoked function expression (IIFE). [Reference](http://benalman.com/news/2010/11/immediately-invoked-function-expression/). – Brett Mar 05 '14 at 19:50
  • Excellent! Really, the only advantage of using the `foo` variable is you could keep a reference around to call that function again if you wanted. The first example would be ideal if you only needed to call the function once. – Mike Christensen Mar 05 '14 at 19:50
2

It is a self invoking function. Meaning a function that declares and calls itself.

Another form would be:

(function() {
    return function() {
    }
}());
beautifulcoder
  • 10,832
  • 3
  • 19
  • 29