What is an IIFE and why would you use one?
An IIFE (immediately invoked function expression) is a function that is defined and called in one go, like (function () { ... })(). It creates a private scope so variables inside do not leak out.
Explain it simply
An IIFE is a temporary workshop: you walk in, do your work, and leave nothing lying around on the shared table. The function runs once, immediately, and every variable inside disappears when it finishes.
Before let, const and modules, this was the main way to avoid polluting the global scope. The extra parentheses tell the parser "this is an expression, not a declaration", which is what lets you call it straight away with ().
Today you mostly see it for one-off async setup ((async () => { ... })()) or in older libraries and bundled code.
Example
(function () {
var secret = "only here";
console.log(secret); // Output: only here
})();
console.log(typeof secret); // Output: undefined
const result = (() => 2 + 3)();
console.log(result); // Output: 5Without the wrapping parentheses, function () {}() is a syntax error, because a statement starting with function must be a named declaration.
What to say in the interview
"An IIFE is a function expression invoked immediately. It gives a private scope, so internals do not leak into the global scope. I'd use it for module-like encapsulation in old code or for top-level await-style setup; with ES modules and block scope it is needed less often."
Common mistakes
- Forgetting the wrapping parentheses and getting a SyntaxError.
- Forgetting the semicolon before an IIFE on the next line, which can merge it with the previous statement.