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

A closure wrapper (function($){..})(jQuery);

is a great way to have local variables instead of globals. Both $

any variable and local function defined inside the shell are only visible inside the shell, not outside. It's great and I use it all the time.

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

      

However, I was wondering why we are passing jQuery

(and possibly other things) as an argument, instead of using a local variable declaration.

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

      

Wouldn't that work just as well and be more transparent?

+3


source to share


2 answers


I see one reason when the old way is better:


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

      





In this example the variable "$" will be undefined due to hoisting.

+5


source


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

For the sake of minimization, it is also possible (and somewhat common) to use an "unset" variable that will serve as a match for undefined like this:



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

      

Since u

no value is passed during the call, it will beundefined

+2


source







All Articles