What is an IIFE (Immediately Invoked Function Expression)?
An IIFE (Immediately Invoked Function Expression) is a function that runs as soon as it's defined, by wrapping it in parentheses and calling it right away.
Purpose — create a private scope so variables don't leak into the global namespace.
Classic use — module-like encapsulation before ES Modules existed.
Less common today: block scoping with let/const and ES Modules cover most of what IIFEs were used for.
// IIFE syntax
(function() {
const secret = 'hidden';
console.log('IIFE executed');
})();
// console.log(secret); // ReferenceError — scoped to IIFE
// Arrow IIFE
(() => {
const config = { debug: true };
// config is private
})();
// IIFE with return value
const counter = (function() {
let count = 0;
return {
increment: () => ++count,
getCount: () => count
};
})();
counter.increment();
console.log(counter.getCount()); // 1
// count is private — not accessible
// IIFE to capture loop variable (pre-let)
for (var i = 0; i < 3; i++) {
(function(j) {
setTimeout(() => console.log(j), 100); // 0, 1, 2
})(i);
}The IIFE creates a private scope — secret is not accessible outside. The counter example returns an object with methods that close over the private count variable (module pattern).
The loop IIFE captures each value of i into a new scope variable j, fixing the classic var+setTimeout bug.
Know the syntax: (function(){})() or (()=>{})(). The module pattern (IIFE returning an object with private state) is the classic use case.
The loop-variable capture is the interview scenario. Modern code uses let/const and modules instead, but IIFEs appear in legacy code and libraries.