As everyone else has said, it's pretty much entirely to do with creating local scope. Another benefit is that you can use it to (for want of a better word) "rename" variables. Take for instance, how several javascript frameworks use $
as a shorthand for their main library function. If you create a closure like in your example, it doesn't matter what $
is outside, you can use it as a parameter and inside it can be whatever you want:
// out here $ might be Prototype, something else, or even undefined
(function($) {
// in here, $ is jQuery
})(jQuery);
Another little tip for eking an extra couple of milliseconds of your script is to use this same technique to create an undefined variable. Most people think that undefined
is a special keyword in javascript, but it's actually just treated as a normal variable, which you'd hope no one would define. The somewhat standard practice of checking for a undefined variable:
if (x == undefined)
...is actually rather wasteful, since it checks the entire scope chain for a variable named "undefined". To shortcut this, you can use this method:
(function($, undefined) {
// code here
})(jQuery); // note that there's just one parameter passed
Now that undefined
is actually in a scope (with an undefined value), checking up the scope chain can stop at that point. Micro-optimisation, yes, but it doesn't hurt to know.