Alex Velickiy
Alex Velickiy

Reputation: 571

IIFE and parameter

Here's a code

(function(x){
    // Some code here
})(1);

The code above is IIFE so this means that it will be executed just once. Qustion: why would anybody need to pass parameter into this function (whick is 1 in example below)?

I can just create variable inside function, like below

(function(){
    var x = 1;
    // Some code here
})();

This question is not about how closures work but about why and when to use first code pattern and when the second one.

Upvotes: 0

Views: 1174

Answers (3)

Ingo Bürk
Ingo Bürk

Reputation: 20043

For one, it can be considered a matter of style. I would prefer

(function (x, y, z) { … })(1, 2, 3);

over

(function () { var x = 1; var y = 2; var z = 3; … })();

if x, y and z are what I would usually pass as a parameter rather than a local variable (so where I declare it depends on what information they hold).

But, in the case of jQuery and other code, what you can essentially do is alias certain names:

(function (window, undefined) {
    // …
})(window);

This snippet does two things:

  • It renamed the global window to a local window. When writing the code, this has absolutely no effect. But when the code is minified, the minifier can rename the IIFE's argument to w – and all usages of it within the function. This way, window only has to be written out one single time, which can potentially save quite a bit of bytes.
  • It declares the parameter undefined, but doesn't pass anything to it. This causes the parameter named undefined to hold the value undefined. It isn't so important anymore these days, but older browsers allow redefining the value of undefined and by doing this, you can make sure no other code will interfere with yours by overwriting the value (which, of course, is a terrible thing to do).

Upvotes: 4

James
James

Reputation: 22247

Consider the difference in the behaviors of these two event handlers:

var tags = document.getElementsByTagName("a");
for (var i=0, t; t = tags[i]; i++) {
  t.addEventListener("click",
    (function (index) { 
      return function () { 
        console.log("iife - " + index); 
      };
    })(i)
  );
  t.addEventListener("click",
    function () { 
      var index = i;
      console.log("non iife - " + index); 
    }
  );    
}

demo

Upvotes: 0

Piyush Chauhan
Piyush Chauhan

Reputation: 1543

The most probable use case is of jQuery.

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

This way no matter what other libraries like Prototype or Mootools you load, your code is always safe inside an IIFE. You can also pass other libraries like Prototype and Mootools using this pattern.

(function($, P, Moo) {
    console.log($);
    console.log(P);
    console.log(Moo);
})(jQuery, $, $$);

Hope this helps!

Upvotes: 1

Related Questions