Thursday, February 10, 2011

Tip of the day: self-executing anonymous functions

As you start digging into some serious JavaScript source code like jQuery, for instance, or when you begin writing a complex JavaScript application or a framework, you will no doubt get to see the following piece of code quite often.



So what is it exactly? As the title suggests, it is called a self-executing anonymous function. What it does is call itself immediately when the script that contains it gets loaded. In other words, if you need something that should execute automatically when the page gets loaded, this is the way - just wrap the instructions in such a function, and you will be sure that they will get executed.

Another common use case for that pattern is protecting your scripts from being interfered by other JavaScript code. Also, one can never be sure that the code that he or she writes is always using the proper instances, or whether some other JavaScript code has not messed up with the global scope variables. JavaScript can be very permissible on many occasions, and even stuff like "undefined = true" gets allowed. You can estimate yourself its impact on your code, unless you have declared what "undefined" is at the very beginning.

John Resig's description of self-executing anonymous funcions

In such cases, a self-executing anonymous function, instantiated with the proper instances of "window", "document", and "undefined" can be very valuable, although they are not mandatory

Again, simply wrap your entire script in such a function, and you can be sure that no external code is messing around with it.