3

I noticed that in some places, jQuery code is wrapped in a self-invoking function like below. Why is this done, in what cases is this useful and in what cases is an unnecessary boilerplate?

function( $ ) {
  ...
}( jQuery );
Sumurai8
  • 20,333
  • 11
  • 66
  • 100
  • you don't need the `$` global variable to represent `jQuery`, there's plenty of duplicates and resources around this. – David Fregoli Jun 26 '13 at 12:16
  • Functions create variable scope. Your function now has a scoped `$`. That's it. –  Jun 26 '13 at 12:20
  • ...but this is unnecessary if your code is put in a `.ready()` handler, since you can just do `jQuery(document).ready(function($) {...});` or the shorter `jQuery(function($) {...});` –  Jun 26 '13 at 12:21

3 Answers3

9

The short answer: To prevent variable name conflicts. It is not always needed, but good practice in order to create conflict free reusable code.

The long answer: In javascript the $ symbol is just another variable. jQuery uses it because it is a nice shorthand instead of having to type out jQuery each time, but so can any other code (including other libraries).

To prevent conflict with other uses of a variable at the same scope (in this case $ at the "global" scope) it is common for code to be wrapped in a self-invoking function with the "conflict-free" variables passed as the function parameters. This then creates a new scope where your variable won't interfere with other uses of that variable. That way you can pass the full named variable & uses it with whatever name you want within the anonymous function.

So, when creating conflict free reusable code it is good practice to use this methodology:

(function( $ ) {
  ...
})( jQuery );

Along these lines you will also see the following format:

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

In this instance undefined is simply used for readability to indicating that no more arguments are passed to the function.

Precastic
  • 3,742
  • 1
  • 24
  • 29
3

In case you want to avoid conflict regarding use of $

function( $ ) {
  ...
}( jQuery );

Inside this function you can use $ without having to worry about it's use outside of it as inside that function, $ always refers to the jQuery object.

This is helpful while creating jQuery plugins,You will see jQuery plugin's use this kind of function to avoid conflicts with other plugins.

Reference : http://learn.jquery.com/plugins/basic-plugin-creation/

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
0

In function scope $ is local variable that not conflict with any other global $.

YD1m
  • 5,845
  • 2
  • 19
  • 23