jQuery question: what does it really mean?

There are already two answers but this is my guess on the missing end of the code:

(function ($, window, undefined) {
  // ... jquery code... 
})(jQuery, window);

Note: three parameters are expected but two are supplied.

What it basically does is:

  1. gives a private scope inside curly braces, so any var declared inside is not visible outside
  2. makes a private $ shortcut to jQuery without relying on this shortcut being set globally (eg. jQuery.noconflict() might have been called and this would still work)
  3. makes a lexical window variable that would mean faster lookups for global variables
  4. makes sure that undefined is indeed undefined in the scope between curly braces, even if someone has written something like undefined = "now it's defined"; in the global scope, because undefined can actually be redefined (this is a mistake of the language).

This pattern is known as immediately invoked function, or immediate function for short, or self-invoking anonymous function, or some other names. The basic idea is that:

(function (x, y) {
    // ...
})(1, 2);

or:

(function (x, y) {
    // ...
}(1, 2));

means the same as:

function myFunction (x, y) {
    // ...
}
myFunction(1, 2);

but without the need to give any name to your function and pollute the namespace.

Going back to your question, this doesn’t mean $(document).ready() or anything like that, but it means that you can use $(document).ready() inside instead of jQuery(document).ready() even if the $ shortcut is not available outside.

This example may actually explain it better, even if it isn’t used anywhere:

(function (JQ, window, undefined) {

    JQ(document).ready(function () {
        // this is run when document is ready
    });

})(jQuery, window);

Now instead of $ you can call jQuery as JQ and use JQ(document).ready() instead of $(document).ready() – it may not seem very useful but it shows what happens when you have a code like that.

As a side note I might add that thanks to this pattern you don’t actually need variable declarations in the language but only function arguments. Instead of:

var x = 10;
alert(x * x * x);

you could use:

(function (x) {
    alert(x * x * x);
})(10);

and indeed a function like this:

function square (x) {
    // some code ...
    var result = x * x;
    return result;
}

is exactly equivalent to:

function square (x, result) {
    // some code ...
    result = x * x;
    return result;
}

because of the hoisting mechanism in JavaScript that would make the result variable available (but undefined) even before the declaration and assignment in both cases (in the // some code ... part). This is often a source of confusion but is actually quite interesting and extremely powerful.

See also my other recently updated answer to the question:
Help understanding JavaScript global abatement techniques
for more info on this subject.

Leave a Comment