What is the purpose of this? (function ($) { //function code here })(jQuery);

I am debugging someone else's JavaScript code and a majority of the code is wrapped like this:

(function ($) {
    //majority of code here...
})(jQuery);

What is going on with the ($) and the (jQuery)? I wasn't taught to code like that and haven't seen them. What is their purpose?

As well, there is no document.ready, but I assume that is because the code is executed right after it's read by the (); at the end?


Solution 1:

var $ = "some value we don't care about";

 // v=====normal plain old function
(function ($) {
 //        ^=======receives jQuery object as the $ parameter

    //majority of code here, where $ === jQuery...

    $('.myclass').do().crazy().things();


})(jQuery);
 //  ^=======immediately invoked, and passed the jQuery object


 // out here, $ is undisturbed
alert( $ ); // "some value we don't care about"

Solution 2:

This is useful when you want / need to use jQuery.noConflict(), and the global name $ isn't an alias for jQuery. The code you posted lets you use the shorter $ to mean jQuery inside the anonymous function only, without $ needing to be a global.

Solution 3:

Just to expand on RightSaidFred's answer a little, when I first saw the ()() syntax I was a bit befuddled, but it made sense once I realised the brackets are being used to define an anonymous function and then call it. e.g:

(function (msg){alert(msg)})('hello');

... defines a function and then calls it, passing 'hello' as a parameter.

So the example in the question:

(function ($) {
    //majority of code here...
})(jQuery);

is passing jQuery into an anonymous function and referring to it as $ within the function, a way of guaranteeing that $ will work for jQuery without interfering with anything else.