What Is an IIFE in JavaScript?
- An Immediately Invoked Function Expression (IIFE) is a function expression that executes immediately after it’s created. Its primary purpose is to create a private scope so variables don’t leak into the global environment.
- Before ES modules and block scope (let / const), IIFEs were one of the most reliable ways to write safe JavaScript.
Basic IIFE Syntax:
Classic IIFE:
code:
(function () {
const secret = 'hidden';
console.log('IIFE ran');
})();
- The function is wrapped in parentheses → making it an expression
- () immediately invokes it
- Variables inside stay private
Alternative IIFE Syntax:
(function () { /.../ }());
!function () { /.../ }();
+function () { /.../ }();
- All of these force JavaScript to treat the function as an expression.
IIFE That Returns a Value:
code:
const result = (function (a, b) {
return a + b;
})(2, 3);
console.log(result); // 5
- Useful when you need a computed value without polluting scope.
Arrow Function IIFE:
code:
(() => {
console.log('Arrow IIFE');
})();
- Shorter and cleaner for simple logic.
Async IIFE (Top-Level Await Alternative):
code:
(async function () {
const data = await fetch('/api/data').then(r => r.json());
console.log(data);
})();
- ✅ Ideal for environments without native top-level await.
Practical Use Cases:
1️⃣ Encapsulation:
- Keep helper variables private. 2️⃣ One-Time Initialization:
- Feature detection, polyfills, event listeners. 3️⃣ Module Pattern:
code:
const Counter = (function () {
let count = 0;
return {
inc() { return ++count; },
get() { return count; }
};
})();
- Creates private state with a public API.
Pitfalls & Best Practices:
- ❌ Overusing IIFEs hurts readability
- ⚠️ Can confuse beginners if undocumented
- ✅ Prefer ES modules for modern apps
- ✅ Use IIFEs mainly for: - Legacy scripts - One-off isolated logic - Immediate async setup
Quick Decision Guide:
| Situation | Recommendation |
|---|---|
| Legacy or single-file script | Use IIFE |
| Need private scope quickly | Use IIFE |
| Modern app / bundler | Use ES modules |
Top comments (0)