A function in JavaScript can be either a statement or an expression. When you use a function expression, you can pass it around like any other value:
> console.log(function() { 1 + 1; });
> (function() {}) && doExpensiveWork();
// etc.
One of the things you can do with a function expression is immediately invoke it. In such cases the function is called an immediately invoked function expression (or IIFE for short):
> (function() { console.log("IIFE running"); })();
IIFE running
This is the same as creating the function and invoking it in two steps:
> var notAnIIFE = function() { console.log("running"); };
> notAnIIFE();
running
A function expression can, of course, take arguments:
> var someFunction = function(x, y) { return x + y; };
> var seven = someFunction(3, 4);
> seven
7
So an IIFE can be invoked with arguments as well:
> var seven = (function(x, y) { return x + y; })(3, 4);
> seven
7
In the case of an invocation like this:
(function($) { /* do work with $ */ })(jQuery);
the value bound to the name jQuery
is being passed into the function expression as the argument $
. This is similar to doing the following:
var initializePlugin = function($) {
/* do work with $ */
};
initializePlugin(jQuery);
but it leaves no trace in the parent namespace (whereas, in our second example, our initializePlugin
name is left behind after we finish setting up our plugin).