Immediately Invoked Function Expressions are function expressions that are immediately invoked. Ok, let's break that down.

First, what is a function expression? In JavaScript we have function declarations and function expressions.

Function declarations look like this:

function myFunction (){
    console.log('This is a function declaration.')
}

Function declarations:

  • Define a named function. The name of the function above is myFunction.
  • Must begin with the function keyword (similarly variable declarations must use the var keyword).
  • Do not require a semicolon after the closing curly brace
  • Does not use a variable assignment (keep reading for more on this)

Function expressions look like these:

var myFunction = function (){
    console.log('This is a function expression, assigned to a variable.')
};

(function(){
    console.log(This is an anonymous function expression that immediately invoked);
})();

Function expressions:

  • Can be named or anonymous.
  • Can be assigned to a variable and invoked using the variable name.
  • Can be invoked immediately.

So, that second function expression example is our IIFE! There are quite a few parentheses in there so let's take a close look.

Here's how we can go about creating an IIFE:

Step 1: create an anonymous function (don't assign it to a variable).

function(){
    console.log(This is an anonymous function);
}

Step2: Wrap the function expression in parentheses.

(function(){
    console.log(This is an anonymous function);
})

Step 3: Invoke the function expression by following it with another set of parentheses & end with a semicolon.

(function(){
    console.log(This is an anonymous function);
})();

This could essentially be done in a few more lines by assigning the anonymous function to a variable and then immediately invoking it by name:

var myFunction = function (){
    console.log('This is a function expression, assigned to a variable.')
};
myFunction();

The main difference is that the very last example stores a named reference to the function expression, while the IIFE does not.

So why would you use an IIFE? Whenever a function is invoked, it created its own execution context. This is why variables defined inside functions are not accessible to the world outside the function. IIFEs are a simple way to create private scope and avoid pollution the global namespace.