Self-executing functions

Update: "Immediate functions" sounds like a much better name.

Self-executable functions are simple and powerful.

All you do is add a set of parentheses after the function and this causes it to be executed right there. If it’s an anonymous function you also need to wrap it in parentheses.

(function(){
   var a = 1;
   var b = 2;
   alert(a + b);
})();

You can also pass parameters to the self-executing function if you want.

(function(a, b){
  var c = a + b;
  alert(c);
})(1, 2);

So how is this pattern useful?

It’s useful when you have some work to do, some initialization maybe. You need to do it only once and you don’t want to leave any globals lying around after the work is finished. All the temporary variables you need like c in the case above remain local and don't pollute the namespace.

Useful also when your code is kind of a guest to the page. Like a bookmarklet for example, or a widget of some sorts. You don’t want to add your variables and functions to the host page’s naming space and possibly causing a naming conflict with the page's core code.

Tags: , ,

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile you can find me on twitter - @stoyanstefanov