Here is another quick tip on creating modular JavaScript, namely function wrappers, or more technically called Immediately-Invoked Function Expression (IIFE). A self-invoking anonymous function runs automatically/immediately when you are create it, but don’t confuse it with document.ready or window.onload.

The basic of IIFE is to use a wrapper so that it does not pollute the global namespace, all variables used inside the function will not be visible to the outside scope. You may have seen this kind of code, something along the line of:

For example the variable defined below bar will not be able to access it outside the scope.
IIFE provides a protection/encapsulation to your code.

If you wish to pass in data to your anonymous function, for example in our code below we are passing in the global window object to our function.

The last benefit of using the IIFE, is that it provides a way to create more modular Javascript.

The code below shows a module called counterModule and how we use it.

And if you have written any JQuery plugin you may have already seen the module pattern used for plugins. In the code below we are injection Jquery into our anonymous function.

This is the very basic of a module pattern, and if you wish to read more about the module pattern I suggest you Addy Osmani book on Javascript Design Patterns