Search code examples
jqueryclosuresdollar-sign

jQuery dollar sign ($) as function argument?


I understand JavaScript closures, and I've seen this done in native JS:

(function () {
  // all JS code here
})();

But, what does adding the jQuery spice do?

(function ($) {
  // all JS code here
})(jQuery);

Solution

  • Its a way of mapping jQuery to the $ in a way so that not all code in a page will see it.

    Maybe you have an existing script that uses jQuery that you like to reuse but you also use prototype that also uses $ in the same page.

    By wrapping any jQuery using code in that construct you redefine $ to jQuery for the contained part without coming into conflict with other code in the page.