16

I have often see expressions such as:

(function () {
    var x = 1;
    ...
}());

How do I interpret it? syntactically, this alone is a anonymous function definition.

function() {
...
}

what the () after that? and why put it in the enclosing ()?

Thanks

Oliver
  • 3,592
  • 8
  • 34
  • 37
  • @delnan: You're right, but I think it is just one of those questions that is a little hard to search for. Although I'll bet that if a person searches *"What is this syntax in javascript"*, they'll come across a few answers. :o) – user113716 Jan 26 '11 at 15:19
  • 2
    @delnan - I think you might be on the wrong website. This is Stack Overflow, where people come for help. Are you lost? Maybe you're on the wrong website perhaps? – jamesmortensen Jan 26 '11 at 15:20
  • @delnan, I assume by asking this question is also learning, but not at the level you like or deem appropriate. I did try to search for it, but didn't get the answer. and For that, I thank @patrick for taking the time to answer me. – Oliver Jan 26 '11 at 15:22
  • @Oliver: Yes, these sorts of questions are welcome here. This particular one comes up frequently, so I think some people get frustrated by it. You can search StackOverflow for duplicates, but this is one that can be hard to know exactly what to search for. – user113716 Jan 26 '11 at 15:26
  • @jmort235: I have absolutely no problem with beginner questions, even with those that have been asked before. But this particular question (along with a few others) is *extremely* frequent. Especially considering that it's not something exotic, but a very common pattern (so explanations for it, and even prompts to adopt it, are equally common). @Oliver: I don't mean to be rude, discourage you from learning, drive you from SO or anything. If it seemed I did, I apologize. It's just a very common question with a (to me) relatively obvious answer. –  Jan 26 '11 at 15:28
  • 1
    I agree that delnan's comment came across as unnecessarily offensive. If the point really is that this question is one people have as frequently as we're led to believe, and that it's that difficult to search for and find the answer, it sounds to me like the Javascript folks need to work on putting together a FAQ. If nothing else, delnan could refer people to that, rather than telling them to learn their language. – Cody Gray - on strike Jan 26 '11 at 15:39
  • 1
    @delna, no need to apologize. there are many things in life that can be annoying or frustrating. please don't let this little question add any weight to it. A pointer to a previous answer would be enough, or ... please just ignore me. – Oliver Jan 26 '11 at 15:56
  • possible duplicate of [Difference between (function(){})(); and function(){}();](http://stackoverflow.com/questions/423228/difference-between-function-and-function) – outis Mar 29 '12 at 01:41

2 Answers2

24

Exactly the same, except that it is being invoked immediately after being converted into a function expression.

// v-----first set of parentheses makes the function an expression
   (function () {
       var x = 1;
       ...
   }());
//  ^-----this set is used to invoke the function

Same as if you did:

   var myfunc = function () {
       var x = 1;
       ...
   };
   myfunc();

or (similar) this:

   var returnValue = function () {
       var x = 1;
       ...
   }();

Get rid of the names, move the parentheses around, and you can see they're not that different.

user113716
  • 318,772
  • 63
  • 451
  • 440
  • hmm, interesting. I guess I need to dig more into the exact meaning of expression and function invoking, thx a lot. – Oliver Jan 26 '11 at 15:19
  • 1
    @Oliver: There are some subtle but important differences between function expressions and declarations. [Here's a really great article](http://kangax.github.com/nfe/) on functions in js. – user113716 Jan 26 '11 at 15:22
  • @user113716 Nice article!. It's clear that the parentheses turn a function declaration into a function expression but it also worth mentioning that: `(function(){}())` and `(function(){})()` happen to be the same. The first one is just Douglas Crockford's style. – Watchmaker Oct 13 '16 at 10:57
2

The area where I most often find this useful is in callback functions. This notation can also used in cases where you need to include a variable in a callback function, but you need the variable state to not be affected by what goes on outside the function.

 var someVal = 1;

 setTimeout( (function(one) {
      return function() {
           alert(one);  // alerts a 1 even 10 seconds after someVal++;
      }
 })(someVal), 10000);

 someVal++;  // the value in the setTimeout will remain the same as it is locked inside.

In this context, setTimeout takes a function that takes no arguments. So the question of how to pass in a value to that function is answered by creating a function that takes one argument that returns a function that takes 0 arguments.

I suggest anyone wanting to learn more about the power of this notation to play around with it in the Firebug JavaScript console. Once you wrap your head around this concept, you'll start to see areas where this powerful concept can be used.

jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
  • what is "IT" called? If it's so hot, it surely must have a name. – Alex Gray Feb 23 '12 at 23:19
  • I think the term you're looking for is a "closure". There are several other uses for closures, many of which I have not yet had the opportunity to explore. – jamesmortensen Feb 24 '12 at 03:24
  • thats what i thought.. but some quick searches pulled up a lot of seemingly unrelated info.. and whats the difference between a `closure` and `clojure`, i wonder? – Alex Gray Feb 24 '12 at 03:29