JavaScript | Immediately Invoked Function Expressions (IIFE)

Functions are one of the building blocks of any programming language and JavaScript has taken the Functions to a whole new level. Functions are said to be a collection of statements to be executed in a proper sequence in a particular context. Now JavaScript provides a variety of methods to define and execute Functions, there are named functions, anonymous functions and then there are Functions that are executed as soon as they are mounted, these functions are known as Immediately Invoked Function Expressions or IIFEs. Let us dive deeper to know more about IIFEs.

Syntax: IIFEs follows a particular syntax as shown below.

(function (){ 
// Function Logic Here. 
})();

Now let us probe some more to understand the relation between the Name and Syntax of this type of Functions.



Why the name Immediately Invoked Function Expressions?

  • Immediately Invoked: This part is easy to explain and demonstrate. This type of function is called immediately invoked as these functions are executed as soon as they are mounted to the stack, it requires no explicit call to invoke the function. If we look at the syntax itself we have two pairs of closed parentheses, the first one contains the logic to be executed and the second one is generally what we include when we invoke a function, the second parenthesis is responsible to tell the compiler that the function expression has to be executed immediately.
  • Function Expressions: It is simple to understand that a Function Expression is a Function that is used as an expression. JavaScript lets us use Functions as Function Expression if we Assign the Function to a variable, wrap the Function within parentheses or put a logical not in front of a function. The following program illustrates the different ways we can create a Function Expression.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Creating Function Expression by assigning to a variable.
    var myFunc = function() { return "GeeksforGeeks"; };
      
    // Creating Function Expression Using Logical Not.
    !function() { return "GeeksforGeeks"; };
      
    // Creating Function Expression Using Parentheses.
    (function() { return "GeeksforGeeks"; });

    chevron_right

    
    

    Now if you look at the third example code it is identical to the first part of the syntax of an IIFE, hence we can conclude that the first part of the IIFE contains a Function Expression while the final part invokes it immediately.

Converting Functions to IIFEs

As we have already seen what an IIFE is and how its syntaxial form can be broken down to make more sense, We can convert a regular function into an IIFE following only two steps as follows.

  • Given any regular function definition, wrap the definition within a closed pair of parentheses, this will create your Function Expression.
  • Lastly add another pair of parentheses and a semicolon to mark the end of the statement, and you have converted your regular Function into an IIFE.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Regular Function.
    function Greet()
    {
        console.log("Welcome to GFG!");
    };
    // Execution of Regular Function.
    Greet();
      
    // IIFE creation and execution.
    (function() { console.log("Welcome to GFG!"); })();

    chevron_right

    
    

    Output:

    Welcome to GFG!
    Welcome to GFG!

Important Points

  1. IIFE follow their own scope like any other function/variable in JavaScript. The part of the name immediately invoked is sometimes confusing to new developers as they expect the IIFE to execute irrespective of function scope, this is wrong. For example, let us take the following example where the IIFE is defined within a function and will only be immediately invoked if we call the Parent Function.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    function myFunc()
    {
        console.log("Welcome to");
        // This will be executed after executing the previous log.
        (function() { console.log("GeeksForGeeks!"); })();
        console.log("Hi There!");
    }
      
    // Calling the Function.
    myFunc();

    chevron_right

    
    

    Output:

    Welcome to
    GeeksForGeeks!
    Hi There!
    
  2. IIFEs have there own scope i.e. the variables you declare in the Function Expression will not be available outside the function.
  3. Similarly to other function IIFEs can also be named or anonymous, but even if an IIFE does have a name it is impossible to refer/invoke it.
  4. IIFEs can also have parameters. For example,
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Declaring the parameter required.
    (function(dt) {
        console.log(dt.toLocaleTimeString());
        // Passing the Parameter.
    })(new Date());

    chevron_right

    
    

    Output:

    4:30:12 PM
    


  5. My Personal Notes arrow_drop_up

    FullStack Developer of six websites Verified Freelancer with 19 complete projects and 4.9 rating Modest Lifelong Learner

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.