Question presented to candidate: "What is an IIFE, why would you use one, and does a variable declared inside one leak out to the surrounding scope?"
What a strong answer should cover:
- 📌 Interview term: IIFE (Immediately Invoked Function Expression) — a function that is defined and called in the same statement, typically written as
(function () { ... })(), running its body immediately without needing a separate, later invocation elsewhere in the code. - 📌 Interview term: the real, direct answer to the prompt — verified directly: a
vardeclared inside an IIFE's body genuinely does not leak into the surrounding scope, because the IIFE's function body creates its own, private scope, exactly like any other function call. - 📌 Interview term: the classic real motivation (pre-ES6) — before
let/const's block scoping existed, an IIFE was the standard way to create a private, isolated scope — avoiding polluting the global scope with helper variables, and (verified directly) fixing the classic var-in-loop-closure bug by wrapping each iteration's body in its own immediately-invoked function, correctly capturing each loop value. - A precise answer names that an IIFE can be written with an arrow function too (
(() => { ... })()), and that the leading parenthesis around the function expression is required specifically to tell the parser it is an expression, not a function declaration (which cannot be immediately invoked the same way). - A precise answer names that IIFEs are genuinely less common today — ES modules already provide their own private, file-level scope, and
let/constblock scoping covers most of the "avoid leaking a helper variable" use case IIFEs used to be needed for — but understanding the pattern remains relevant for reading legacy code and library-bundling output.
Clarifying questions expected:
- None — this is a definitional/technical question; directly answering whether a variable leaks (with real proof) is the strong signal.
Code / implementation expected: Yes — a real IIFE demonstrating both its immediate execution and its private-scope guarantee is the clearest, most convincing proof.