Self-invoking function jQuery

Sumurai8 picture Sumurai8 · Jun 26, 2013 · Viewed 11.2k times · Source

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 );

Answer

Precastic picture Precastic · Jun 26, 2013

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.