JavaScript Notes
Learn JavaScript IIFE (Immediately Invoked Function Expression) – syntax, scope isolation, module pattern, avoid global pollution, named IIFE, async IIFE with real examples.
Introduction
An IIFE (pronounced "iffy") stands for Immediately Invoked Function Expression. It's a function that defines itself and calls itself at the same time — in a single statement.
IIFEs were the go-to pattern in pre-ES6 JavaScript for creating private scope and avoiding global variable pollution. Even today, they appear in legacy code, third-party libraries, and certain modern patterns like async IIFEs.
Basic Syntax
(function () {
console.log("I run immediately!");
})();I run immediately!
Alternative Syntax (both are valid):
// Style 1 – invocation outside the wrapping parens
(function () {
console.log("Style 1");
})();
// Style 2 – invocation inside the wrapping parens
(function () {
console.log("Style 2");
}());Style 1 Style 2
Why the Outer Parentheses?
Without the outer parentheses, the JavaScript parser sees function as the first word and interprets it as a function declaration — declarations must have a name and cannot be immediately invoked.
// This would be a SyntaxError:
function () {
console.log("Hello");
}(); // Error: Function statements require a function nameThe wrapping ( ) forces the parser to treat it as an expression, which can be invoked immediately.
PARSER LOGIC:
function() {} → DECLARATION? needs a name → SyntaxError!
(function(){}) → EXPRESSION? ✅ no name needed → can invoke immediately!IIFE with Parameters
You can pass arguments to an IIFE just like any other function call.
(function (name, greeting) {
console.log(`${greeting}, ${name}!`);
})("Riya", "Namaste");Namaste, Riya!
Classic Pattern – Passing window, document, or libraries:
(function ($, window) {
// Inside here: $ is guaranteed to be jQuery
// window is the global scope
console.log("jQuery and window available privately");
})(jQuery, window);This pattern was common in jQuery plugins to avoid naming conflicts.
IIFE Return Value
An IIFE can return a value, which you can capture.
const result = (function (a, b) {
return a + b;
})(10, 20);
console.log(result);30
Step-by-Step Execution Trace
const config = (function () {
const apiUrl = "https://api.example.com";
const timeout = 5000;
return {
getUrl: function () { return apiUrl; },
getTimeout: function () { return timeout; }
};
})();
console.log(config.getUrl());
console.log(config.getTimeout());
console.log(config.apiUrl); // private – undefinedhttps://api.example.com 5000 undefined
Memory Diagram – IIFE Scope Isolation
IIFEs create a private sandbox — variables inside never pollute the global scope.
Real World Analogy
An IIFE is like a one-time-use pop-up store. It opens (function starts), does its business (runs code), and closes (function ends) — all in one moment. You can grab what it offers (return value) before it disappears, but everything inside the store is gone once it closes. 🏪 No permanent storefront (no global variables) 📦 Just grab what you need and the shop is gone
IIFE for Module Pattern (Legacy)
Before ES modules (import/export), IIFEs were used to create modules with private state.
const BankAccount = (function () {
// private – inaccessible from outside
let balance = 0;
const INTEREST_RATE = 0.05;
// public API
return {
deposit: function (amount) {
balance += amount;
console.log(`Deposited ${amount}. Balance: ${balance}`);
},
withdraw: function (amount) {
if (amount > balance) {
console.log("Insufficient funds!");
return;
}
balance -= amount;
console.log(`Withdrew ${amount}. Balance: ${balance}`);
},
getBalance: function () {
return balance;
},
addInterest: function () {
balance += balance * INTEREST_RATE;
console.log(`Interest added. Balance: ${balance}`);
}
};
})();
BankAccount.deposit(1000);
BankAccount.deposit(500);
BankAccount.withdraw(200);
BankAccount.addInterest();
console.log(BankAccount.getBalance());
console.log(BankAccount.balance); // private!Deposited 1000. Balance: 1000 Deposited 500. Balance: 1500 Withdrew 200. Balance: 1300 Interest added. Balance: 1365 1365 undefined
Arrow Function IIFE (ES6+)
Arrow IIFE runs immediately!
42
Async IIFE
A common modern use case: running await at the top level (in environments that don't support top-level await).
(async function () {
const data = await Promise.resolve({ user: "Riya", score: 95 });
console.log(data.user, data.score);
})();Riya 95
IIFE vs Block Scope (ES6+)
In modern JavaScript, let and const with block scope {} can replace simple IIFEs used only for scope isolation.
// Old way – IIFE for scope isolation
(function () {
var temp = "I'm private";
console.log(temp);
})();
// console.log(temp); → ReferenceError
// Modern way – block scope
{
let temp = "I'm also private";
console.log(temp);
}
// console.log(temp); → ReferenceErrorI'm private I'm also private
When to still use IIFE in modern code:
- Async IIFE for top-level await
- Returning a value from initialization code
- Encapsulating a larger module
- Compatibility with legacy environments
Common Mistakes
❌ Mistake 1: Missing the wrapping parentheses
// WRONG – SyntaxError
function () {
console.log("Hello");
}();// CORRECT
(function () {
console.log("Hello");
})();❌ Mistake 2: Missing semicolon before IIFE in some contexts
// Can cause issues if previous line has no semicolon
const x = 5
(function() { console.log(x); })()
// JS reads: const x = 5(function()...)() → TypeError!// Safe – add semicolon before or after
const x = 5;
(function () { console.log(x); })();5
❌ Mistake 3: Expecting IIFE to run again
const result = (function () {
return Math.random();
})();
// result is a fixed number – IIFE ran only ONCE
console.log(result);
console.log(result); // same value – not recalculated0.7823... 0.7823...
IIFEs run once. If you need repeated execution, use a regular function.
IIFE Use Cases
| Use Case | How IIFE Helps |
|---|---|
| Avoid global variable pollution | Variables stay inside IIFE scope |
| Initialize configuration | Run setup code once, return config object |
| Module pattern (legacy) | Private state + public API |
| Async top-level code | Wrap await calls |
| Third-party library plugins | Avoid naming conflicts |
| Legacy browser code (var scope) | Simulate block scope |
Interview Questions
Q1. What is an IIFE?
An IIFE (Immediately Invoked Function Expression) is a function expression that is defined and called in a single statement. It runs exactly once and creates its own private scope.
Q2. Why do we wrap the function in parentheses?
Without parentheses, the JavaScript parser treats function as the start of a function declaration, which requires a name and can't be immediately invoked. The parentheses force it to be parsed as an expression.
Q3. What problem does IIFE solve?
IIFE prevents variables from leaking into the global scope. Variables inside an IIFE are private — they can't be accessed from outside, avoiding naming conflicts.
Q4. Can an IIFE receive parameters?
Yes. You pass arguments in the invocation parentheses: (function(x, y) { ... })(arg1, arg2).
Q5. Can an IIFE return a value?
Yes. The return value can be assigned to a variable: const result = (function() { return 42; })();
Q6. How does IIFE relate to closures?
An IIFE can use closures — its inner functions can reference variables declared inside the IIFE, creating private state accessible only through the returned public API.
Q7. When is IIFE still useful in modern JavaScript?
- Async IIFE for top-level
awaitwithout top-level await support - Initialization that returns a complex object
- Legacy code maintenance
- When you need to execute a function and capture its result in one line
Q8. What is the difference between IIFE and a block scope ({})?
An IIFE creates a function scope — works with var too. A block {} only creates block scope for let/const, not for var. IIFEs can also return values; blocks cannot.
Key Takeaways
- ✅ IIFE = Immediately Invoked Function Expression — runs once, instantly
- ✅ Outer
( )makes the function an expression so it can be invoked - ✅ Creates a private scope — variables inside don't pollute global scope
- ✅ Can accept arguments and return values
- ✅ Classic tool for the module pattern (private state + public API)
- ✅ Used for async top-level code with
async functionIIFE - ✅ In modern code, block scope (
let/constin{}) often replaces simple IIFEs - ✅ Always add semicolons before IIFE to avoid parsing issues
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript IIFE Explained – Immediately Invoked Function Expression.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, functions, iife, javascript iife explained – immediately invoked function expression
Related JavaScript Master Course Topics