IIFE(Immediately Invoked Function Expression)

IIFE(Immediately Invoked Function Expression)

In this Blog we are going to learn about IIFE and its uses.

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that is immediately executed as soon as it is defined. It is a concise way to create a new scope for your code and execute it right away.

Here's a simplified definition of an IIFE:

An IIFE is a function that is declared and invoked in the same line, creating a self-contained scope and executing its code immediately.

Here's a simple example of an IIFE:

(function() {
  console.log("This is an IIFE!");
})();

In this example, the anonymous function is defined and immediately invoked using ( ) at the end. The function body contains a console.log statement, which will be executed immediately. As a result, the message "This is an IIFE!" will be printed to the console.

IIFEs are often used to encapsulate code and avoid polluting the global scope. They can also be useful for creating private variables and functions. Here's an example that demonstrates how an IIFE can be used to create a private variable:

var result = (function() {
  var secret = "This is a secret message.";
  return secret;
})();

console.log(result); // Output: "This is a secret message."
console.log(secret); // Output: ReferenceError: secret is not defined

In this example, the IIFE returns the value of the secret variable, which is then assigned to the result variable. The secret variable is only accessible within the IIFE's scope and cannot be accessed from outside, as indicated by the ReferenceError when trying to log its value.

IIFEs provide a way to create isolated scopes and execute code immediately, making them useful for various scenarios in JavaScript development.

Simple Def and Code to Remember

IIFE - Immediately Invoked Function Expression

  • this practice was popular due to var.

  • Immediately invoking a function avoids - the re-declaration of variables inside it

// Immediately invoked function expressions
(function(){
      var x = 1;   // this var is now protected
})()


(function(a){
      var x = a;   // this var is now protected
})(2)