Immediately Invoked Function Expression ES6

Immediately Invoked Function Expression (IIFE)

Immediately Invoked Function Expression (IIFE) is a JavaScript function used to ignore the variable hoisting from inside the code block. An IIFE is a function that runs when we define it. The Immediately Invoked Function Expression allows us to access the method publicly; while it is managing the privacy for variables declared inside a function. The IIEF is also named as Self-Executing Anonymous Functions.

The Immediately Invoked Function Expression includes the following two parts-

  • It is enclosed with a Grouping Operator ().
  • It is used to interpret functions directly by the JavaScript engine.

Syntax

(function ()
 {
        // Block statement
 }) (); 

Example

Here, we have tried to elaborate the concept of IIFE with the help of following example.

(function ()
 {
        console.log (“An Example of IIFE”);
 }) (); 

Output

After the execution of the code, we will get the following output.

Immediately Invoked Function Expression

Function conversion into IIFEs

Some steps are given below that helps us to convert the function into Immediately Invoked Function Expression-

Step 1: First, we take a regular function definition.

Step 2: Then, we bind that definition with the parentheses to create the function expression.

Step 3: In the final step, we associate the expression with the parentheses ({}) and a semicolon (:) as the sign of ending of the statement.

We will try to understand it with the help of the following example-

Example

function alpha ()                                       // Regular Function
 {
      Console.log (“Normal Function”);     
 };
       alpha ();                                                 // Execution of Regular Function
 (function ()                                                 // Declaration and Execution of IIFE
 {                                                                 
                Console.log (“An Immediately Invoked Function Expression”);
 }) ();  

Output

After the execution of the above code, we will get the following output.

Immediately Invoked Function Expression

Some important points about IIFE

Example

(function (p, q, r) 
 {
                console.log (p);
                      console.log (q);
 console.log (r);
 }) (50, 150, 100);  

Output

After the compilation of the code, we will get the following output.

Immediately Invoked Function Expression