How does the (function() {})() construct work and why do people use it?

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.


1) It defines an anonymous function and executes it straight away.

2) It's usually done so as not to pollute the global namespace with unwanted code.

3) You need to expose some methods from it, anything declared inside will be "private", for example:

MyLib = (function(){
    // other private stuff here
    return {
        init: function(){
        }
    };

})();

Or, alternatively:

MyLib = {};
(function({
    MyLib.foo = function(){
    }
}));

The point is, there are many ways you can use it, but the result stays the same.


It's just an anonymous function that is called immediately. You could first create the function and then call it, and you get the same effect:

(function(){ ... })();

works as:

temp = function(){ ... };
temp();

You can also do the same with a named function:

function temp() { ... }
temp();

The code that you call jQuery-specific is only that in the sense that you use the jQuery object in it. It's just an anonymous function with a parameter, that is called immediately.

You can do the same thing in two steps, and you can do it with any parameters you like:

temp = function(answer){ ... };
temp(42);

The problem that this solves is that it creates a closuse for the code in the function. You can declare variables in it without polluting the global namespace, thus reducing the risk of conflicts when using one script along with another.

In the specific case for jQuery you use it in compatibility mode where it doesn't declare the name $ as an alias for jQuery. By sending in the jQuery object into the closure and naming the parameter $ you can still use the same syntax as without compatibility mode.


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
})();

Tags:

Javascript