Immediately-Invoked Function Expressions (IIFE)

i

Before reading you should probably know about; Function Expressions Vs Declarations.

An Immediately-Invoked Function Expression(or IIFE, pronounced “iffy”) is an anonymous function expression that is immediately invoked or executed after it is created. The most common convention is shown below.

// Anonymous IIFE 
(function(){ 
    // Function body 
})();

Parenthesis() are wrapped around the whole function. Without them, the parser interprets the expression as a function declaration and when it first reads function it then expects to see a name for that function rather than the () which results in a SyntaxError stating that the “function statement requires a name”. The () wrapping the function explicitly tells the parser that the function is an expression and since expressions can be anonymous we can then invoke the function without errors.

In short the () enforce a function expression.

The () appended to the end of the function invokes the function and allows arguments to be passed in.

// Anonymous IIFE 
(function(param1, param2){ 
    // Function body 
})(arg1, arg2);

There are several other ways to trick the parser though they are uncommon in implementation.

!function () { … }(); 
~function () { … }(); 
-function () { … }(); 
+function () { … }();

IIFE’s assigned to variables

You can assign an IIFE to a variable, creating a function expression. We do not need to wrap this kind of IIFE in () as the compiler will not confuse it for a function declaration.

var module = function(param1, param2){ 
    return 'An IIFE'; 
}(arg1, arg2);

Using the this keyword

You can also immediately invoke a function and force the context of this at the same time with Function.call or Function.apply.

var module = function(param1, param2){ 
    return 'An IIFE invoked with Function.call'; 
}.call(this, arg1, arg2);

Did you find the article helpful?
Show your ❤ with the click of a button, then tell all your friends.

(If you have liked this article before but find yourself coming back for reference please throw a ❤ my way each time you return and find it of help.)

What do you reckon?

Your email address will not be published. Required fields are marked*

*

!

An error has occured with your submition. Sorry there is no further details, if the problem persists please use the contact form to inform us.