⚡ JavaScript Functions Deep Dive #3: Understanding IIFE (Immediately Invoked Function Expressions)

JavaScript is full of surprises — and one of its cleverest patterns is the Immediately Invoked Function Expression (IIFE). If you’ve ever seen a function that executes as soon as it’s defined, you’ve seen an IIFE in action.
In this post, we’ll demystify:
What an IIFE is
Why it exists
How it works
When and where to use it
🧠 What Is an IIFE?
An Immediately Invoked Function Expression (IIFE) is a function that runs immediately after it is defined.
🔸 Syntax:
(function () {
console.log("I ran immediately!");
})();
✅ Output: "I ran immediately!"
✅ IIFE Breakdown
Concept | Explanation |
Function Expression | Wrapped in () to treat it as a value |
Immediately Invoked | Followed by () to execute it right away |
Private Scope | Creates a new execution context — variables inside won’t leak out |
🔍 Why Do We Need IIFEs?
Before ES6 introduced let
and const
(which support block scope), JavaScript only had function scope. IIFEs gave developers a way to create isolated scopes to:
Avoid polluting the global namespace
Encapsulate private variables
Avoid conflicts between scripts
🧪 Example: Using IIFE for Isolation
var user = "global";
(function () {
var user = "scoped";
console.log(user); // "scoped"
})();
console.log(user); // "global"
💡 The variable user
inside the IIFE does not affect the global user
. Also we did not need to create a named function declaration and make an explicit function call.
🧰 Use Cases for IIFEs
Use Case | Description |
✅ Scope isolation | Avoid variable collisions in global scope |
✅ Module pattern | Used in early JS to create private data |
✅ One-time setup | Initialization code that runs once (e.g., configs, caching) |
✅ Loop variable capture | Used with var loops to preserve variable values in async callbacks |
🧪 IIFE in a for
Loop (Pre-ES6)
for (var i = 0; i < 3; i++) {
(function (j) {
setTimeout(() => console.log(j), 100);
})(i);
}
// Output: 0 1 2
Without the IIFE, you'd get 3 3 3
because var
is not block-scoped.
🧑💻 Variations of IIFE Syntax
Form | Syntax | Notes |
Classic | (function() { ... })(); | Most common |
Arrow | (() => { ... })(); | Works like regular IIFE |
With parameters | (function(name) { ... })("Alice"); | Pass arguments directly |
Example with parameters:
(function(name) {
console.log(`Hello, ${name}`);
})("Pushpesh");
🚫 When Not to Use IIFEs
When you're using
let
andconst
— modern block scoping often makes IIFEs unnecessary.When you need reusable logic (IIFEs run once).
When readability is more important than cleverness.
✅ Recap
Feature | IIFE |
✅ Runs immediately | Yes |
✅ Creates private scope | Yes |
🧠 Useful before ES6 | Very |
✅ Still used in tooling/modules | Yes |
❌ Good for multiple uses | No (runs only once) |
Subscribe to my newsletter
Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
