Posts Tagged ‘self-executing’

Self-executing functions

Tuesday, September 15th, 2009

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.

   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;
})(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.