Immediately Invoked Function Expression (IIFE)

It is a JavaScript function that runs as soon as it defined. An IIFE (Immediately Invoked Function Expression) can be used for avoiding the variable hoisting from within the blocks. It allows the public access to methods while retaining the privacy for variables defined in the function.

IIFE is a design pattern that is also known as the Self-Executing Anonymous Function. It contains two major parts:

  • The first part is the anonymous function having a lexical scope, which is enclosed within the Grouping operator ().
  • The second part creates the IIFE by which the JavaScript engine will interpret the function directly.
Syntax
(function () 
{
    statements
})();

// Syntax of IIFE with ES6 arrow functions (though parentheses only allowed on outside)

(() => { /* ... */ })();

Let us try to understand the concept of IIFE by using the following example.

Example
snippet
(function()
 {
 console.log("Hello World"); 
})();
Output
Hello World

Conversion of Functions into IIFEs

We can convert the regular functions into IIFE by using the following steps:

  • Suppose any regular function definition.
  • Wrap that definition within the pair of parentheses, which will create the function expression.
  • At last, we have to add a pair of parentheses and a semicolon for marking the end of the statement.

Let's see the illustration for the same in the following example:

Example
snippet
// Regular Function. 
function hello() 
{ 
    console.log("Regular function"); 
}; 
// Regular Function execution. 
hello(); 
  
// IIFE creation and execution. 
(function() { console.log("Immediately Invoked Function Expression"); })();
Output
Regular function Immediately Invoked Function Expression

Key points about IIFEs

  • Immediately invoked function expressions (IIFEs) have their scope. The variables declared in the function expression will not be available outside the function.
  • Like other functions, IIFEs can also be anonymous or named.
  • IIFEs can also be parameterized. For example,
Example
snippet
(function (x, y, z) {
   console.log(x);
   console.log(y);
   console.log(z);
 })(100, 200, 300);
Output
100 200 300
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +