Learn the concept
IIFE (Immediately Invoked Function Expression)
An IIFE is a function expression that is defined and executed immediately, creating a private scope to avoid polluting the global namespace.
An Immediately Invoked Function Expression (IIFE) is a JavaScript design pattern where a function is created and executed in a single step. The function is wrapped in parentheses to make it an expression (not a declaration), then immediately called with trailing ().
Before ES6, JavaScript only had function scope via var — there was no let, const, or block scoping. The only way to create a new scope was with a function. IIFEs solved three problems:
Avoiding global pollution — Variables inside an IIFE don't leak to the global scope. Libraries like jQuery wrapped their entire codebase in an IIFE.
The Module Pattern — Combining an IIFE with closures creates private variables and a public API:
const Counter = (function () {
let count = 0; // private — not accessible outside
return {
increment() { return ++count; },
getCount() { return count; }
};
})();
Counter.increment(); // 1
Counter.count; // undefined — privatevar in loops, all closures share the same variable. An IIFE captures the current value per iteration:for (var i = 0; i < 3; i++) {
(function (j) {
setTimeout(() => console.log(j), 100);
})(i); // Logs 0, 1, 2 — not 3, 3, 3
}With ES6 modules, let/const, and block scoping, most IIFE use cases are solved natively. However, IIFEs still appear in legacy code, bundler output, <script> tags without type="module", and frequently in interview output-based questions testing scope and closure understanding.
// Classic IIFE
(function () {
const secret = 42;
console.log(secret); // 42
})();
// console.log(secret); // ReferenceError — not in scope
// Arrow function IIFE
(() => {
const msg = 'Hello from IIFE';
console.log(msg);
})();
// IIFE with arguments
(function (global, doc) {
console.log(global === window); // true
console.log(doc === document); // true
})(window, document);
// IIFE returning a value
const result = (function () {
return 2 + 2;
})();
console.log(result); // 4Libraries like jQuery and Lodash wrap their entire codebase in an IIFE to avoid adding variables to the global scope and conflicting with other scripts.
When loading multiple scripts via <script> tags, IIFEs prevent variable name collisions between scripts that share the global scope.
Create a todo list module using the IIFE module pattern with private state (tasks array) and public methods (add, remove, getAll, count). No ES6 modules allowed.