Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Immediately-invoked Function Expressions (IIFE)

Nested functions (or inner functions) in JavaScript are a useful feature. They are functions inside another function. Learn how to create a nested function. How variable scopes, closures & lexical scopes work. Also learn to create multi-level nested function, passing parameters to them etc

Immediately invoked Function Expressions

                            
(function() {
    // statements
})()
                
                        
                            
                        

To create an IIFE, first, create a function. Note that we have not given any name to the function (i.e. functional declaration syntax), not assigned it to some variable (like in function expression)

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

Wrap it inside the bracket.

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

Finally, we need to execute it. To do that add parentheses at the end with a value for each parameter inside the parentheses

                            
(
  function(a,b) {
    console.log(a+b)
  }
)(1,2);
 
 
**** Result ***
//3
  
                            
                        
                            
                        

Adding the parentheses will invoke the IIFE immediately.

We need to add the trailing semicolon if we use two IIFE one after another. Otherwise code won’t work.

                            
(function () {
...
}()) // no semicolon
(function () {
...
}());
                      
                            
                        

Named IIFE

You can also give a name to IIFE.

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

But you cannot use that name call the function

                            
addNum();  //Uncaught ReferenceError: addNum is not defined
 
                            
                        
                            
                        

Need for IIFE

IIFE was used to create new JavaScript Scope before the arrival of the let & const keyword in ES6 and the block scope

Take a look at the following code. The someVar variable is declared inside the if condition. But you can access it outside the if condition also.

                            
function someFunc() {
  cond = true;
 
  if (cond) {
    var someVar = "some Variable";
    //More Statements
  }
 
  //someVar can be accessed here
  console.log(someVar); "some Variable";
}
 
someFunc();
                          
                        
                            
                        

Now moving the if condition inside an IIFE creates a new function scope. We now cannot access the variables declared inside the IIFE. Accessing the someVar results in an error.

                            
function someFunc() {
  cond = true;
 
  ( function () {
    if (cond) {
      var someVar = "some Variable";
      //More Statements
    }
  })();
 
  //Uncaught ReferenceError: someVar is not defined
  console.log(someVar);
 
}
 
someFunc();
                          
                        
                            
                        

But since the ES6, we can use the let (or const) instead of var.

                            
function someFunc() {
  cond = true;
 
  if (cond) {
    let someVar = "some Variable";
    //More Statements
  }
 
  console.log(someVar);
  //Uncaught ReferenceError: someVar is not defined
}
 
someFunc();
                          
                        
                            
                        

Similarly, the following code creates a block scope around curly braces Hence the variable i is invisible outside the curly braces. Without the let statement only way to achieve this is using the IIFE.

                            
{
  let i=10;
  //Some Statements
}
 
console.log(i);   //Uncaught ReferenceError: i is not defined