Skip to content

JavaScript IIFE | Immediately Invoked Function Expression Example code

  • by

JavaScript IIFE stands for an immediately invoked function expression. It defined as a function expression and executed immediately after creation.

It is a design pattern which is also known as a Self-Executing Anonymous Function

Syntax

Defining an immediately invoked function expression:

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

Immediately invoked function expression (IIFE) Example

Let’s see the HTML example of the function becomes a function expression that is immediately executed.

<!DOCTYPE html>
<html>

<head>
    <script>

        // Regular Function. 
        function msg() 
        { 
            console.log("Welcome to EyeHunts!"); 
        }; 
        // Execution of Regular Function. 
        msg(); 

        // IIFE creation and execution. 
        (function() { console.log("Welcome!"); })(); 

    </script>

</head>
<body>

</body>
</html>

Output:

JavaScript IIFE Immediately Invoked Function Expression

Note: The variable within the function expression can not be accessed from outside it.

Do comment if you have any doubts and suggestion on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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