JavaScript Fundamentals / Functions

IIFE (Immediately Invoked Function Expression)

‼️ IIFE in Action

Immediately Invoked Function Expressions (IIFE) are JavaScript functions that are executed immediately after they are defined. They are typically used to create a local scope for variables to prevent them from polluting the global scope.

Syntax:

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

➡️ You can also use arrow functions:

(() => {
  console.log("IIFE using arrow function");
})();

📌 Why Do We Use IIFE?

Without IIFE:

var count = 0;

This count is in the global scope — any script can access or overwrite it.

With IIFE:

(function () {
  var count = 0; // private
})();

Now, count is safe and isolated inside the function.

Example: Here's a basic example of an IIFE .

(function() {
 // IIFE code block
    var localVar = 'This is a local variable';
    console.log(localVar); // Output: This is a local variable
 })();

Explanation: The function is wrapped in parentheses (function() { ... }), followed by () to immediately invoke it.


✅ Use Cases of IIFE

Use Case

Explanation

Avoid polluting the global namespace

Variables inside IIFE are scoped locally, so they don’t interfere with global variables.

Create closures

IIFE helps in capturing and preserving data in a private scope — useful in loops or function factories.

Create private and public variables/methods

IIFE allows defining private variables inside the function and exposing only what's returned (Module Pattern).

Execute async/await functions immediately

You can use IIFE with async to handle asynchronous operations at runtime.

Work with require function (in Node.js)

IIFE can be used to immediately execute code that loads modules or files using require.