Immediately-Invoked Function Expressions 101

Immediately-Invoked Function Expressions or IIFEs (pronounced like iffys) are one of the least understood core JavaScript concepts I’ve encountered when interviewing new candidates or engaging with new clients. 8 out of 10 have no idea what an IIFE is. 1 out of 10 can regurgitate the definition from Wikipedia. Only 1 out of 100 though actually know how to use it properly. Ben Alman has an article on his blog, though a few years old, explains this concept in full really well link. Here’s a couple of major points on it.

What is an Immediately-Invoked Function Expression?

In interviews I generally don’t beat around the bush and just ask “What is an IIFE?”. The answer I’m hoping for is like: “An anonymous function executed immediately. This function also maintains a local scope which allows us to avoid dirtying the global scope.”

So what’s the benefit?

Using IIFEs keeps the global scope cleaner and avoids unnecessary references from being created and existing beyond their expected lifetime. Your variable coolVar if not properly scoped ends up hanging on to the Window object longer than you want which can lead to security risks and an increased memory footprint or leak.

How do I use an Immediately-Invoked Function Expressions?

So if somehow we can get to this question, understanding how we use it in code is another story. The best example of lack of knowledge to this is the question “How can I use $ to get access to jQuery instead of jQuery?”. Using jQuery.noConflict() relinquishes the control of the $ from jQuery. This is useful when other libraries want to make use of $, which is extremely popular. So how can we use $ for jQuery after jQuery.noConflict() has been invoked? This is where using an IIFE comes into play.

jQuery.noConflict();
(function($) {
    // Access to $ is available now
})(jQuery);

By using an IIFE, we can now access the $ for jQuery while at the same time relinquishing control of the $ outside of the IIFE so some other library can also use this. This is how we avoid dirtying the global object.

This can also be used to create your own libraries and exposing a single variable and not exposing all the functionality globally.

var Lib = (function(w, d) {
    Lib = function() {
    };

    Lib.prototype = {
        myMethod: function() {
        },

        otherMethod: function() {
        }
    };
    

    return Lib;

})(window, document);

This now allows us to call Lib.myMethod and allows for multiple instances of Lib if needed.

Conclusion

IIFEs are an extremely important part of JavaScript whether we fully understand them or not. Having more understanding of them though will allow you to make decisions when coding out a Single Page Application.