Meet IIFE - the Quintessential JavaScript Closure

If you want to call yourself a JavaScript bad-ass, then there is at least one little code pattern you should know by heart: the Immediately Invoked Function Expression (IIFE). This pattern defines a function that is executed immediately and it looks like this:

(function () { alert("Hello world, I'm an IIFE!"); }());

This is an important pattern primarily because it provides a closure for initialization code, which allows you to keep temporary variables out of the global scope. That is to say, it encloses code in a function that acts as a scope wrapper or sandbox and that is executed immediately after it’s created. I find it easier to remember this pattern by breaking it down into the following steps…

JavaScript IIFE in 4 simple steps

  1. Define a function using a function expression.
    function() {};
  2. Add a set of parentheses at the end, which causes the function to be executed immediately.
    function() {}();
  3. Wrap the whole function in parentheses.This is required because we’re not assigning the function to a variable.
    (function() {}());
  4. Write the function body.…in the usual spot between the curly braces.
    (function () { alert("Hello world, I'm an IIFE!"); }());

You can use this pattern any time you need to create a scope sandbox. You can also use it instead of jQuery’s $( document ).ready() when you’re actually able to follow the best-practice of loading render-blocking scripts last. You will almost certainly use this pattern when creating your own reusable JavaScript library or framework. When using an IIFE in your own library, you will likely use a more complex form – passing in parameters. In an upcoming post, I’ll show you how to do that, so stay tuned.