Loading...
JavaScript

What is IIFE in JavaScript?

An IIFE (Immediately Invoked Function Expression) pronounced as iify is a JavaScript function that runs as soon as it is defined. In other words, the function gets executed automatically as soon as the page loads. There is no need to call this function anywhere in the script. JavaScript engine directly interprets the function.

The syntax:

(function () {
    statements
})();

IIFE is also known as Self-Executing Anonymous Function. This type of function has no name and hence it is called an anonymous function.

Example:

var greet= (function () {
    var message= "Hello there!"; 
    return message; 
})(); 
// Immediately creates the output: 
"Hello there"

Note: The variables and functions defined within the IIFE anonymous function are not accessible from the code outside it. Therefore, an Immediately Invoked Function Expression is a good way to protect the scope of your function and the variables within it. For example, if you try to access the variable message from outside scope, it will throw “Uncaught ReferenceError: message is not defined” error.

var greet= (function () {
    var message= "Hello there!"; 
    return message; 
})(); 

// Variable message is not accessible from the outside scope
alert(message) // throws "Uncaught ReferenceError: message is not defined"

If you found this useful, please leave your thoughts in the comment box below and follow us.

Share this article with your friends
Leave a Reply

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