For one, it can be considered a matter of style. I would prefer
(function (x, y, z) { … })(1, 2, 3);
over
(function () { var x = 1; var y = 2; var z = 3; … })();
if x
, y
and z
are what I would usually pass as a parameter rather than a local variable (so where I declare it depends on what information they hold).
But, in the case of jQuery and other code, what you can essentially do is alias certain names:
(function (window, undefined) {
// …
})(window);
This snippet does two things:
- It renamed the global
window
to a local window
. When writing the code, this has absolutely no effect. But when the code is minified, the minifier can rename the IIFE's argument to w
– and all usages of it within the function. This way, window
only has to be written out one single time, which can potentially save quite a bit of bytes.
- It declares the parameter
undefined
, but doesn't pass anything to it. This causes the parameter named undefined
to hold the value undefined
. It isn't so important anymore these days, but older browsers allow redefining the value of undefined
and by doing this, you can make sure no other code will interfere with yours by overwriting the value (which, of course, is a terrible thing to do).