What is Immediately Invoked Function Expression(IIFE)?

Immediately Invoked Function Expression(IIFE) is a function that runs as soon as it is defined. Immediately Invoked Function Expression is an important concept in Javascript. In fact, many of the frameworks and libraries built on Javascript use Immediately Invoked Function Expression.

In this section, we will look at how to define and use the Immediately Invoked Function Expression.

Before we dive into IIFE’s let us first look at how functions are defined in Javascript.

function sum(a, b) {
    console.log(a + b);
}

Here, we have a simple function declaration which takes two parameters and adds them up. This function does not execute until we call the function. To call the function we can invoke the function as below:

sum(5, 10); // 15

As we know that functions in Javascript are first call functions, we can also assign them to a variable.

sum = function (a, b) {
    console.log(a + b);
}

Again, to invoke the function we use the same statement.

sum(5, 10); // 15

If we try to declare an anonymous function without assigning it to a variable we will get a syntax error.

function(a, b) {
    console.log(a + b);
}

// Uncaught SyntaxError

If you wrap the function in parentheses, Javascript will no longer complain. However, it is not a useful function because it does not get invoked.

(function(a, b) {
    console.log(a + b);
});

Using the parentheses after the function declaration will invoke the function.

(function(a, b) {
    console.log(a + b);
})(5, 6);

//Output: 11

This function is now an Immediately Invoked Function Expression because the function gets executed immediately after it is declared.

You may also find a different syntax used to call the IIFE like below:

(function(a, b) {
    console.log(a + b);
}(5, 6));

Both the syntax are valid and do the same thing of invoking the function immediately after it is declared.

We can also use the function expression to invoke a function immediately.

var sum = (function(a, b) {
    console.log(a + b);
}(5, 1));

//Output: 6

But do note that if you try to refer to the value stored in variable sum it will be undefined.

console.log(sum); // undefined

If the function, however, returns a value, it gets assigned to the variable sum.

var sum = (function(a, b) {
    console.log(a + b);
    return "hello world";
}(5, 1));

console.log(sum); // hello world