An IIFE is a JavaScript function that is defined and executed immediately after it is created.
Syntax:
(function () {
console.log("IIFE executed");
})();
or (arrow function):
(() => {
console.log("IIFE executed");
})();
✅ Why Is IIFE Used?
✔ 1. Avoid Global Scope Pollution
Variables inside an IIFE stay private.
(function () {
var secret = "hidden";
})();
console.log(secret); // ❌ ReferenceError
✔ 2. Create a Private Scope
Before let and const, IIFE was the main way to create block-like scope.
(function () {
var count = 0;
console.log(count);
})();
✔ 3. Execute Code Only Once
Useful for:
- initialization logic
- configuration setup
- one-time calculations
const config = (() => {
return { apiUrl: "https://api.com" };
})();
✔ 4. Avoid Variable Name Conflicts
Especially useful in large codebases or older JS.
(function () {
var name = "Teekam";
})();
✔ 5. Used in Module Patterns
Before ES6 modules.
const counter = (function () {
let count = 0;
return {
increment() {
count++;
return count;
}
};
})();
🔥 When Should You Use IIFE?
✔ One-time setup code
✔ Protect variables from global scope
✔ Creating private data
✔ Legacy JavaScript (pre-ES6)
✔ Library initialization
❌ When NOT Needed Today?
- When using ES6 modules (
import/export) - When using block scope (
let,const)
Modern code relies less on IIFE, but it’s still important to understand.
🎯 Short Interview Answer
An IIFE is a function that runs immediately after being defined.
It is used to create a private scope, avoid polluting the global namespace, and run one-time initialization logic.
IIFEs were widely used before ES6 modules andlet/const.