Search code examples
javascriptiife

Javascript Syntax: Immediately Invoked Function Expression (IIFE) with parameters


I have always seen code like this:

(function(){
   //code here
})();

How does this code work? Which function receives which parameters?

(function(factory){
   //code here
}(function($){
  //other code here
}));

Solution

  • function($){
      //other code here
    }
    

    This block is passed as a parameter to the outer IIFE. It might be clearer to write it like this:

    var factoryDef = function($) { ... };
    
    (function(factory) {
        // this is the outer IIFE
        var someVar = {};
        // you can call:
        factory(someVar);
        // the previous line calls factoryDef with param someVar
    }(factoryDef));
    

    So factory(someVar) is the same as factoryDef({}); the latter is simply the value of factory (which is the function factoryDef) called with the value of someVar (which is {}.)

    Does that make sense?