IIFE

What is IIFE in Javascript?

What is IIFE?

IIFE stands for Immediately Invoked Function Expression. Its a Javascript function which runs as soon as it defined.  It is Also called as anonymous function which means it does not have any name.

Syntax:

(function () { 
  // Line Of Code 
})();

Due to the parenthesis () on last line, its also called as Self-Executing Anonymous Function.

Example of IIFE

(function(value){ 
  var greet = 'Hello'; 
  console.log(greet+ ' ' + value); 
})('IIFEs'); // Hello IIFEs"

When javascript engine execute above code it will create global execution context when it sees code and create function object in memory for IIFE. When function is Invoked a new execution context is created on the fly and so greet variable goes into that function execution context not into the global this is what makes it unique.

Why we use IIFE?

  • Data privacy : The main reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the outside world. i.e, If you try to access variables with IIFE then it throws an error as below.
    (function () {
      var str = "IIFE";
      console.log(str);
    })();
    console.log(str); // "ReferenceError: str is not defined"
  • Prevent conflicts between script files : In our application there may be  many functions and global variables from different source files, it’s important to limit the number of global variables. If we have some initiation code that we don’t need to use again, we could use the IIFE pattern. As we will not reuse the code again, using IIFE in this case is better than using a function declaration or a function expression.
    (() => { 
      // some initiation code 
      let first; 
      let second; 
    })();
    
    // first and second will be discarded after the function is executed.
  • To use as an argument when a function is called — anonymous functions & IIFE

    var sum = (function (num1, num2)
    {
    return num1 + num2;
    })(45,45);
    console.log(sum); // 90

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *