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: , ,

3 Responses to “Self-executing functions”

  1. Alva Giannecchini Says:

    awesome bless you for composing this

  2. Avi Says:

    I didn’t understand the part of:
    “…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.”
    How can this scenario happen?
    Can you give me an example?

  3. Karl Says:

    @Avi - I think the author is trying to get across that the variables and functions inside a self-executing anon function will not be global and therefore won’t clobber any variables / functions that may already exist in the global namespace, i.e. if you declare a var / function without namespacing it or using a particular function pattern it will be part of the global namespace, i.e. the window object in a browser, hope this helps….

Leave a Reply