Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pass jQuery as an argument to (function($){..})(jQuery) closure wrapper, instead of local var?

The closure wrapper (function($){..})(jQuery); is a great way to have local variables instead of global ones. Both $ and any variable and local function defined within the wrapper is visible only within the wrapper, not outside. This is great, and I use it all the time.

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

However, I have been wondering why we pass jQuery (and possibly other stuff) as an argument, instead of using a local variable declaration.

(function(){
  var $ = jQuery;
  [..]
})();

Wouldn't this work just as fine, and be more transparent?

like image 830
donquixote Avatar asked Feb 10 '23 10:02

donquixote


2 Answers

I see one reason when former way is better:

(function(){
  var $ = jQuery;
  [..]
  var jQuery = foo;
})();

In this example variable "$" will be undefined because of hoisting.

like image 158
Rafał Łużyński Avatar answered Feb 12 '23 00:02

Rafał Łużyński


There's an advantage in terms of code length. It saves a few characters (bytes...). It's not much, but if you have to choose between the 2, the first example is shorter.

In the sake of minification, it's also possible (and to some degree common) to use an "unset" variable to serve as an undefined match like this:

(function(r,u){if(r.missingProp===u)alert('undefined!')})({realProp:1})

Since u isn't passed a value during the call, it will equal undefined

like image 27
Amit Avatar answered Feb 11 '23 23:02

Amit