Search code examples
jqueryiife

What does it mean whenever a function ends with })(jQuery);?


I tried googleing, but Google doesn't seem to care about parentheses...


Solution

  • If you see this:

    (function($) {
        // ...code using $...
    })(jQuery);
    

    It's doing two things:

    1. Defining an anonymous function that uses $ as its reference to jQuery.
    2. Calling it, passing in jQuery.

    You could do it like this:

    function foo($) {
        // ...code using $...
    }
    foo(jQuery);
    

    ...but that creates an unnecessary symbol.

    All of this is because jQuery has the symbol jQuery and the symbol $, but it's not uncommon for people to use jQuery.noConflict() to tell jQuery to return $ back to whatever it was when jQuery loaded, because a couple of other popular libraries (Prototype and MooTools, to name two) use $ and this lets someone use those libraries and jQuery together. But you can still use $ within your function, because the argument shadows whatever that symbol means outside the function.