JavaScript scope and closure

The point of this is that any variables declared in the cool stuff will not be created in global namespace. Any function in javascript will create such a scope. Suppose you have some javascript you want to run. If you do this:

var b = 1; 
// stuff using b

And some other code uses b, it will get your left over value. (Or, even worse, if some other code sets b before your code runs, then tries to get its old value later, you'd have changed it in the meantime.)

On the other hand, if you have this code, which declares and then calls the a function:

function a() { 
     var b = 1;
}

a();

And some other code later on uses b, it will not see your values, since b is local to the function. The problem with this, of course, is that you're still making a global name - "a", in this case. So, we want a function with no name - this is why you get the code you described. It declares a function with no name, and then calls it.

Unfortunately, you can't just say:

function() { ... }()

because this will be parsed as a function declaration statement, and then a syntax error. By wrapping the function declaration in parenthesis, you get a function expression, which can then be called. You call it like any other function expression (like a, above), using the second set of parens. For example, if the function took arguments, you'd pass them there:

(function(a) { ... })(1)

That creates a function, calls it, and discards it.

It might be clearer if you look at it like this:

var throwaway = function(){
    // do cool stuff
};
throwaway();

This is done to create a private namespace. Code in the function can have functions and variables without worrying about conflicting with other code loaded in the page.


i just came across this post recently. This type of function definition & call is called self-invoking functions.

(function(){  //code })();

The code inside the function will be executed immediately upon its definition.