JAVASCRIPT | IMMEDIATELY INVOKED FUNCTION EXPRESSION (IIFE) | ADVANCE JAVASCRIPT

Share the post
IIFE

IMMEDIATELY INVOKED FUNCTION EXPRESSION (IIFE) IN JAVASCRIPT

Hello All,
Many of you who are web developers are already known the concept of Immediately Invoked Function Expression (IIFE) in JavaScript. In this topic we will discuss What is IIFE ? Example of IIFE to understand it in better way and What are the advantages of IIFE ? So, let’s start…

What is Immediately Invoked Function Expression (IIFE) ?

IIFE is the function that invoked & defined at the same time. It means that it will automatically called after it get’s defined.
Suppose you have the same function name which was created by mistake of some developers. It possible while you have more than one developer working on the same project. They both gave the same name of function & then called it. After calling the same function name JavaScript will only execute the function which are write earliest but it will called both the function which are having same name & execute the result of second function as the second function will override the first function.
Example :

<html>
<head>
    <h1>JAVASCRIPT : Immediately Invoked Function Expression – IIFE</h1>
    <style>
    </style>
</head>
<body>
</body>
</html>
<script>
    function a() {
        console.log(“a by function 1”);
    }
    function a() {
        console.log(“a by function 2”);
    }
    a();
</script>
As shown in above example we can see that second function result is consoled on log. If we use this functions inside the IIFE then this problem get’s resolved. How ? let’s see this.
The function which are declared under IIFE will not affect the global scope variable or functions. 
It will restrict the function to become a global function Or it will restrict the variable to become a global variable.

Syntax Of IIFE :


(function(){
    // CODE HERE
})();

Example using IIFE :


<html>
<head>
    <h1>JAVASCRIPT : Immediately Invoked Function Experssion – IIFE</h1>
    <style>
    </style>
</head>
<body>
</body>
</html>
<script>
    (function () {
        function a() {
            console.log(“a by function 1”);
        }
        a();
    })();
    (function () {
        function a() {
            console.log(“a by function 2”);
        }
        a();
    })();
</script>

Output :


a by function 1
a by function 2
As seen in above example, Even though the name of the function is same but JavaScript not override the result as they called under IIFE. So, thus proved that IIFE are restrict the function to become a global function.

Advantages of IIFE :

  • Very useful while create minified version of JS.
  • Overriding of function & variable can be avoided.
  • Can able to maintain & organize the JS.
  • Avoid errors.

Leave a Comment