JavaScript: Why the anonymous function wrapper?

(function() {})() and its jQuery-specific cousin (function($) {})(jQuery) pop up all the time in Javascript code.

How do these constructs work, and what problems do they solve?

Examples appreciated


Solution 1:

With the increasing popularity of JavaScript frameworks, the $ sign was used in many different occasions. So, to alleviate possible clashes, you can use those constructs:

(function ($){
  // Your code using $ here.
})(jQuery);

Specifically, that's an anonymous function declaration which gets executed immediately passing the main jQuery object as parameter. Inside that function, you can use $ to refer to that object, without worrying about other frameworks being in scope as well.

Solution 2:

This is a technique used to limit variable scope; it's the only way to prevent variables from polluting the global namespace.

var bar = 1; // bar is now part of the global namespace
alert(bar);

(function () {
   var foo = 1; // foo has function scope
   alert(foo); 
   // code to be executed goes here
})();