IIFE in JavaScript: Syntax, Closures & Modules

Easy100% Free~12 mins#iife#closures#module-pattern#scope#var
Interview Answer (30-Second Summary)

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})();
8
9counter.inc();
10counter.inc();
11console.log(counter.get(), typeof count);
12
13for (var i = 0; i < 3; i++) {
14 (function (j) {
15 setTimeout(function () { console.log('iife', j); }, 0);
16 })(i);
17}
18
19const result = (() => 'arrow iife')();
20console.log(result);
Predict Console Output
Interactive Challenge

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.

Call Stack (Top = Active)
Global
IIFE
Lexical Scope / Bindings
count (private):0
counter:{ inc, get }
Console Stream
> [empty]

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.

  1. Private state (module pattern): variables inside the IIFE exist only in that call. The returned inc and get are closures, so they can keep using count, while outside code cannot see it at all (typeof count is 'undefined').
  2. Capturing loop values: with var i, every timer callback would share one i and print 3 three times. Calling an IIFE per iteration copies the current value into its parameter j. Today let i does the same job.
  3. Timing: the IIFE body runs immediately, but setTimeout still queues its callback, so the synchronous console.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.

Q1.
What is an IIFE in JavaScript?

An Immediately Invoked Function Expression: a function written as an expression and called straight away, as in (function () { ... })() or (() => { ... })(). The code inside runs once, in its own scope.

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.

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 ... })().

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'.

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.

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.

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