IIFE (Immediately Invoked Function Expression) is a JavaScript function that is defined and executed immediately after it is created.
🔹 What is an IIFE?
(function () {
console.log("I run immediately");
})();
or (arrow function):
(() => {
console.log("I run immediately");
})();
🧠 Why We Need IIFE in JavaScript
1️⃣ Avoid Polluting the Global Scope
Before ES6, JavaScript had no block scope.
var count = 10;
Using IIFE:
(function () {
var count = 10;
})();
✔ count is private
✔ Not accessible globally
2️⃣ Create Private Variables (Encapsulation)
const counter = (function () {
let count = 0;
return {
increment() {
count++;
console.log(count);
}
};
})();
counter.increment(); // 1
counter.increment(); // 2
✔ Data privacy
✔ Closure-based state
3️⃣ Execute Code Immediately
Useful for setup logic.
(function init() {
console.log("App initialized");
})();
4️⃣ Avoid Variable Name Conflicts
Especially in large or third-party scripts.
(function () {
var user = "Admin";
})();
5️⃣ Module Pattern (Before ES Modules)
IIFE was used to simulate modules.
const app = (function () {
function start() {
console.log("Started");
}
return { start };
})();
❓ Why Parentheses Are Needed
JavaScript treats function() as a declaration.
Wrapping it in () turns it into an expression, which can be executed immediately.
❌ Do We Still Need IIFE Today?
Less than before, because:
letandconstprovide block scope- ES Modules provide proper modules
But IIFE is still useful: ✔ For quick isolated execution
✔ In legacy code
✔ For one-time setup logic
🎯 Short Interview Answer
An IIFE is a function that runs immediately after it is defined.
It is used to create a private scope, avoid global variable pollution, and execute setup code instantly.
Before ES6 modules, IIFEs were commonly used to implement the module pattern.
⭐ One-line summary
IIFE creates an isolated scope and runs immediately to protect variables and avoid global pollution.