Immediately Invoked Function Expression (IIFE) in JavaScript

🚀 What is an IIFE?

An Immediately Invoked Function Expression (IIFE) is a function in JavaScript that runs as soon as it is defined. It's a common pattern used to create a new scope and avoid polluting the global namespace.

Note

💡 IIFE stands for "Immediately Invoked Function Expression", and it's used to execute a function immediately after its definition.

📌 Syntax of an IIFE

Basic IIFE Syntax

(function () {
  console.log("IIFE executed!");
})();

The function is wrapped in parentheses to convert it into an expression, and the final () immediately invokes it.

🧠 Why Use IIFE?

  • 📦 Encapsulate code and create a private scope
  • 🚫 Avoid polluting the global scope
  • ✅ Useful in module patterns
  • 🔁 Create closures in loops

🔐 Example: Private Scope

Using IIFE for Data Privacy

const counter = (function () {
  let count = 0;
  return {
    increment() {
      count++;
      return count;
    },
    decrement() {
      count--;
      return count;
    }
  };
})();

console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.count); // undefined

The variable count is not accessible from the outside — it's safely encapsulated inside the IIFE. 🔒

📦 Parameterized IIFE

You can also pass arguments into an IIFE:

IIFE with Parameters

(function (name) {
  console.log(`Hello, ${name}!`);
})("JavaScript"); // Hello, JavaScript!

🌀 IIFE in Loops (Classic Use Case)

Closure Fix Using IIFE

for (var i = 0; i < 3; i++) {
  (function (j) {
    setTimeout(function () {
      console.log(j);
    }, j * 1000);
  })(i);
}

// Logs 0, 1, 2 with 1-second intervals

Note

🧠 Each loop iteration creates a new scope for j — preserving the correct value.

⚠️ Common Mistake: Forgetting the Extra Parentheses

A function declaration like function test() by itself is invalid when followed by (). So wrapping in () turns it into a function expression.

📚 Summary

FeaturePurpose
EncapsulationCreates private scopes
Global ScopeAvoids polluting it
UsageModules, loops, privacy

🔗 External References

>>“JavaScript’s flexibility allows patterns like IIFE to help us write cleaner, more secure code.”