Thursday, December 09, 2010

JavaScript self-executing anonymous function

In JavaScript you can write anonymous function as follow…

  
   (function(){
       var foo = 'Hello World';
   })();

   alert(foo);  //will get Error undefine foo

now you may argue that, why would I ever want to use self-executing function this way? Where I could always do...

 
   var foo = 'Hello World';
   alert(foo);

Yes definitely you can do that but this way you will create foo object that is a global object and you may never ever use it again…

In conclusion self-executing anonymous function is useful for time where
you want to avoid polluting the global namespace with your code.