- JavaScript
- Execution Contexts, Closures, and Object Prototypes
- IIFE: Immediately Invoked Function Expressions
IIFE in JavaScript: Syntax, Closures & Modules
An IIFE in JavaScript (Immediately Invoked Function Expression) is a function expression that runs as soon as it is defined: (function () { ... })(). Its variables stay private to that call, so it was the standard way to create private state and modules, and to capture loop values with var, before let, const and ES modules.
Key Learning Objectives
Write an IIFE in its common forms, including arrow and async IIFEs.
Use an IIFE to create private state with the module pattern.
Explain how an IIFE captured loop values with var before let existed.
Know why a leading semicolon protects an IIFE.
The Interview Problem
In what order are the five lines printed, and what does typeof count give outside the IIFE?
1var counter = (function () {2 var count = 0;3 return {4 inc: function () { return ++count; },5 get: function () { return count; },6 };7})();89counter.inc();10counter.inc();11console.log(counter.get(), typeof count);1213for (var i = 0; i < 3; i++) {14 (function (j) {15 setTimeout(function () { console.log('iife', j); }, 0);16 })(i);17}1819const result = (() => 'arrow iife')();20console.log(result);
Predict Console Output
Select the option that matches what this code prints to the console:
2 undefined / arrow iife / iife 0 / iife 1 / iife 2
2 number / arrow iife / iife 0 / iife 1 / iife 2
2 undefined / arrow iife / iife 3 / iife 3 / iife 3
2 undefined / iife 0 / iife 1 / iife 2 / arrow iife
V8 Engine Execution Trace
Step 1 of 5 (Line 7)The function expression is called as soon as it is defined. It returns an object whose methods close over count.
IIFE in JavaScript Explained
What an IIFE in JavaScript Does
An IIFE is a function expression that is called right where it is written: (function () { ... })(). The parentheses turn the function into an expression; the final () calls it.
- Private state (module pattern): variables inside the IIFE exist only in that call. The returned
incandgetare closures, so they can keep usingcount, while outside code cannot see it at all (typeof countis'undefined'). - Capturing loop values: with
var i, every timer callback would share oneiand print 3 three times. Calling an IIFE per iteration copies the current value into its parameterj. Todaylet idoes the same job. - Timing: the IIFE body runs immediately, but
setTimeoutstill queues its callback, so the synchronousconsole.log(result)prints before the timers. Start an IIFE with;when the previous line may lack one, or(will be read as a call on that line's value.
Common Traps & Mistakes
Writing function () { ... }() without wrapping parentheses, which is a syntax error at the start of a statement.
Leaving out the semicolon before an IIFE, so the previous line's value is called as a function.
Expecting the IIFE to make setTimeout run immediately; it only captures the value.
FAANG Follow-Up Probes
Probe #1
Rewrite the loop so it prints 0, 1, 2 without an IIFE.
Probe #2
How would you turn the counter IIFE into an ES module?
Probe #3
Why do bundlers wrap code in IIFEs in their output?
IIFE in JavaScript Interview Questions
Key interview inquiries, edge cases, and architectural follow-ups for IIFE: Immediately Invoked Function Expressions.
Why are the parentheses around the function needed?
A line that starts with the function keyword is parsed as a function declaration, which cannot be called on the spot. Wrapping it in parentheses (or starting with !, + or void) makes the parser read it as an expression, which can be invoked immediately.
Why use an IIFE?
To keep variables out of the outer or global scope, to create private state (the module pattern), to capture a value for each loop iteration when using var, and to run async code with await in places where top-level await is not available: (async () => { await ... })().
How does an IIFE create private variables?
Variables declared inside the IIFE live only in that call's scope. Functions returned from it keep access through a closure, so counter.inc() can change count, but no outside code can read count directly; typeof count outside is 'undefined'.
Why do some IIFEs start with a semicolon?
Without a semicolon at the end of the previous line, ( on the next line is read as a function call on the previous value. const b = 2 followed by (function () {})() throws TypeError: 2 is not a function. A leading ; makes the IIFE safe to paste anywhere.
Are IIFEs still needed with let, const and ES modules?
Much less. Block-scoped let fixes the loop-capture problem, and ES modules give every file its own scope. IIFEs still appear in bundler output, in scripts that must run without modules, and as async IIFEs.
What is the difference between an IIFE and a closure?
An IIFE is a way of calling a function; a closure is a function that remembers the scope it was created in. They are often used together: the IIFE creates the scope once, and the functions it returns are closures over it.
More JavaScript interview questions for freshers
