2015-01-28

Immediately Invoked Functional Expressions (IIFEs) in JavaScript

References:
  • Wikipedia
  • http://gregfranko.com/blog/i-love-my-iife/
  • http://nicoespeon.com/en/2013/05/properly-isolate-variables-in-javascript
  • http://benalman.com/news/2010/11/immediately-invoked-function-expression/

A example for general use:

TL;DR
(function(ourcode){ourcode($,window,document)}(function($,window,document){/*do protected stuff*/}))

 /*
  * i.    There are two function expressions.
  *
  * ii.   The purpose of this outer IIFE is cosmetic, to display the global
  *       variables passed into the inner IIFE, at the TOP of your script.
  *       Otherwise they would be displayed at the bottom, e.g.
  *
  *         function(){
  *           // our spiffy code
  *         }(window.jQuery, window, document);
  *
  * iii.  In the inner IIFE, '$,' 'window,' and 'document,' are parameter names, 
  *       and therefore locally scoped. WE'RE NOT REFERRING TO GLOBALS.
  * 
  */



( function(ourcode) 
  {   
    console.log('Outer IFFE: I did not wait - I was simply invoked before the Inner IFFE.')
    ourcode(window.jQuery, window, document);
    console.log('Outer IFFE: I did not wait - I was simply invoked after the Inner IFFE.')
  }(  function($, window, document) 
      {   

        // Here, finally, lies the code we wanted to execute.

        $(function() {

          // Code that MUST wait for the DOM to be ready goes here. 
          console.log('Inner IFFE: I waited - I was invoked within $(like_this) ')

        });

        // Code that does NOT need to wait for the DOM to be ready goes here. 
        console.log('Inner IFFE: I did not wait - I was simply invoked.')

      }   
    )   
);