Sub topic 12
Immediately Invoked Function Expressions
This chapter assumes you know how function expressions work, how let and const create block scope, and how a returned inner function can keep using variables from its outer function (a closure).
An immediately invoked function expression (IIFE) is a function expression that is defined and called in the same statement. It runs once, at the point where it appears. Any variables declared inside it stay private to that call.
The Basic Shape
An IIFE has two parts: a function expression wrapped in parentheses, then a call () straight after it.
(function () {
const message = 'Runs right away';
console.log(message); // Runs right away
})();
console.log(typeof message); // "undefined"The wrapping parentheses matter. When a statement starts with the keyword function, the parser reads it as a function declaration. A declaration needs a name and can't be called in place, so function () {}() is a SyntaxError. Inside parentheses, the parser expects an expression, so the same code becomes a function expression that you can call at once.
You can also put the call parentheses inside the wrapper, as in (function () { ... }()). Both forms behave the same, so choose one and use it consistently.
Arrow Function IIFEs
Arrow functions work too, but only one placement of the parentheses is valid:
const total = (() => {
const prices = [4, 6, 10];
return prices.reduce((sum, p) => sum + p, 0);
})();
console.log(total); // 20With an arrow, the parentheses must wrap the arrow function itself, as in (() => {})(). Writing (() => {}()) is a SyntaxError, because an arrow function's body can't be followed directly by a call.
Creating Private State
The classic use of an IIFE is to set up private state once and hand back only what callers need:
const id = (function () {
let next = 0;
return function () {
next += 1;
return next;
};
})();
console.log(id()); // 1
console.log(id()); // 2The IIFE runs one time. It creates next and returns the inner function, which is then assigned to id. No outer code can read or reset next. Only id can reach it, through its closure.
Async IIFEs
Top-level await works only in ES modules. In a CommonJS script, or in any other place where you can't use top-level await, an async IIFE lets you write await code without naming a function:
(async () => {
const value = await Promise.resolve(42);
console.log(value); // 42
})();Errors thrown inside an async IIFE become a rejected promise. Add a try/catch inside it, or a .catch() on the result, so failures aren't silently dropped.
Common Error: Missing Semicolons
If the line before an IIFE has no semicolon, automatic semicolon insertion may not add one. The opening parenthesis then becomes a call on the previous line's value:
const base = 10;
const result = base
;(function () {
console.log('Safe because of the leading semicolon');
})();
console.log(result); // 10Without the ;, JavaScript reads the code as base(function () { ... })() and throws TypeError: base is not a function. Code styles that skip semicolons usually put a leading ; in front of every IIFE for this reason.
When You Still Need One
| Goal | Older approach | Modern alternative |
|---|---|---|
| Keep temporary variables private | IIFE | A `{ }` block with `let`/`const` |
| Keep a file's variables out of the global scope | IIFE around the whole file | ES modules |
| Compute a `const` with multi-step logic | IIFE | Still an IIFE, or a named helper function |
| Use `await` outside a module | Async IIFE | Async IIFE |
Exercise
Why does function () { console.log('hi'); }(); throw a SyntaxError, and what is the smallest change that makes it run immediately?
Show answer
A statement that starts with function is parsed as a function declaration. A declaration needs a name and can't be invoked in place. Wrapping the function in parentheses, (function () { console.log('hi'); })();, makes it an expression that can be called immediately.
Exercise
Rewrite the id counter as an arrow function IIFE that returns an arrow function.
Show answer
const id = (() => { let next = 0; return () => ++next; })(); Calling id() returns 1, then 2, and next stays private.