Anjan Dutta

Javascript iife - Immediately invoked function expression

Javascript iife - Immediately invoked function expression

iife is the way of immediately calling a function, right after its definition.

These are self executing functions and they don't pollute the global scope.

Below is an example iife function in javascript.

(function () {
console.log('Example 1 iife');
})();

Output

Parameterized iife

Here, the function definition is enclosed within a pair of brackets. This ensures that we are creating an separate scope for our iife.

At the end, the opening and closing brackets () invokes the function.

Arrow function

iife works with arrow functions.

For instance, both of the below examples are valid.

(() => {
console.log('Example 2 iife');
})();

Output

Arrow function

Parameterized iife

Like other functions, an IIFE can accept parameters and can return values.

Here is an example of parameterized iife.

(function (num1, num2) {
let result = num1 + num2;
console.log(result);
})(2, 3);

Output

Parameterized iife

Use case

Take the above code snippet as an example.

We see that there are three variables used in the function, i.e. num1, num2, result.

And as soon as the function executes, all three of these variables are cleared out of the lexical scope.

This ensures that the global scope doesn't store unused variables.