Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I reference jQuery in a self contained function?

(function ($, undefined) {

    . . .

})(jQuery);

I see this everywhere, but I don't understand why we're sending jQuery as a parameter in a self contained function. jQuery is already being referenced. Also, why are we defining undefined as a parameter?

like image 377
BenR Avatar asked Apr 01 '14 19:04

BenR


1 Answers

Passing $ to the anonymous function ensures that the namespace is protected (i.e. does not conflict with other libraries that also use the $ shortcut).

Oftentimes, undefined is passed to a function to ensure that the variable is truly undefined. For example, consider the following code exerpt:

undefined = '123';
if(myVar == undefined)
{
    // Will only ever execute if myVar == '123'
}

As noted in the comments though, unless you're writing a plugin or some such, using jQuery(function($) { }) is probably a better approach, since it protects the $ shortcut and also provides a DOMReady event, meaning less code is required to achieve the same result.

If you need to check against undefined, you might also want to consider using $.noop().

like image 178
BenM Avatar answered Oct 23 '22 11:10

BenM