It's often used to ensure all variables used in the code take their values from this snippet of code only - local scope. They ignore variables defined outside of the snippet.
var a = 10;
(function() {
alert(a); // undefined
var a = 5;
alert(a); // 5
})();
Its other main use is to ensure code will work in one Javascript library (eg. jQuery) even when there are multiple libraries (eg. Prototype, Mootools) being used on the page. You'd do something like...
(function($) {
alert('test');
// You can now use the jQuery $ in here
// And not worry about the Prototype $ being used instead
})(jQuery);
By passing the jQuery
object into the function, it gets the local-scope variable name of $
, which will take precedence over the global-scoped Prototype $
(which has completely different methods available).