Sub topic 12
Immediately Invoked Function Expressions
This chapter assumes you know how function expressions differ from declarations and how hoisting treats each one. It also assumes you know that var is function-scoped while let and const are block-scoped, and that this depends on how a regular function is called.
An immediately invoked function expression (IIFE, pronounced "iffy") is a function expression that is called as soon as it is created. It runs once. Any variables it declares belong to a fresh function scope, so they do not leak into the surrounding code. Before let, const, and ES modules existed, an IIFE was the main way to get a private scope in JavaScript. You will still find IIFEs in older libraries, in bundler output, and in code that needs await where top-level await is not available.
The Basic Shape
const id = (function () {
let next = 0;
return function () {
next += 1;
return next;
};
})();
console.log(id()); // 1
console.log(id()); // 2
console.log(typeof next); // "undefined"The outer function runs once and returns the inner function. The inner function is a closure over next, so it can read and change next on every call. Code outside cannot reach next at all. The IIFE has finished running, but next stays alive because the returned function still refers to it.
The pattern has two parts:
(function () { ... })turns the function into an expression.- The trailing
()calls that expression straight away.
Why the Parentheses Are Required
When a statement begins with the function keyword, the parser reads it as a function declaration. A declaration is not a value, so you cannot call it in the same statement.
These attempts fail:
// SyntaxError: function statements require a function name
// function () { console.log('hi'); }();
// SyntaxError: unexpected token ')'
// function run() { console.log('hi'); }();Anything that puts the parser in expression position fixes this. Wrapping the function in parentheses is the convention, but there are other ways:
(function () { console.log('a'); })(); // call outside the parens
(function () { console.log('b'); }()); // call inside the parens
!function () { console.log('c'); }(); // unary operator
void function () { console.log('d'); }(); // void operator
const result = function () { return 'e'; }(); // right side of assignment
console.log(result); // eAll five run their function. The two parenthesized forms behave the same, and which one you use is a style choice. Minifiers often emit the ! form because it is one character shorter. The unary forms throw away the return value (! negates it and void discards it), so use them only for side effects.
Passing Arguments In
The trailing parentheses are an ordinary call, so you can pass arguments. Older libraries used this to give global objects short local names, or to lock in a value at the time the IIFE runs.
const config = { debug: true };
const logger = (function (settings, prefix) {
return {
log(message) {
if (settings.debug) {
console.log(`${prefix} ${message}`);
}
}
};
})(config, '[app]');
logger.log('started'); // [app] startedThe Module Pattern
Return an object from an IIFE and you get a module. Its methods share private state that nothing else can touch. This is usually called the revealing module pattern.
const cart = (function () {
const items = [];
function add(name, price) {
items.push({ name, price });
}
function total() {
return items.reduce((sum, item) => sum + item.price, 0);
}
return { add, total };
})();
cart.add('pen', 2);
cart.add('book', 12);
console.log(cart.total()); // 14
console.log(cart.items); // undefineditems is private. The only way to change it is through add, which keeps the data consistent. ES modules give the same guarantee more simply: anything you do not export is private to the file.
Capturing Loop Values: The Historical Use
With var, a loop has a single variable for the whole function, so every closure created inside the loop sees the final value:
var broken = [];
for (var i = 0; i < 3; i++) {
broken.push(function () { return i; });
}
console.log(broken.map(f => f())); // [ 3, 3, 3 ]
var fixed = [];
for (var j = 0; j < 3; j++) {
(function (captured) {
fixed.push(function () { return captured; });
})(j);
}
console.log(fixed.map(f => f())); // [ 0, 1, 2 ]
const modern = [];
for (let k = 0; k < 3; k++) {
modern.push(() => k);
}
console.log(modern.map(f => f())); // [ 0, 1, 2 ]In the fixed version, each IIFE call creates a new scope with its own captured parameter. With let, each loop iteration gets its own binding, so you no longer need the IIFE. If you find this pattern in legacy code, replacing var with let is usually a safe refactor.
Arrow Function IIFEs
An arrow function can be invoked immediately too, but the parentheses must wrap the arrow itself:
(() => {
console.log('arrow IIFE');
})();
// SyntaxError: the call cannot attach to the arrow's body
// () => { console.log('nope'); }();The (function () {}()) style, with the call inside the parentheses, does not work for arrows. An arrow function is not allowed to appear directly before call parentheses. Write (() => {})() every time.
The two IIFE flavors also handle this differently. A regular function IIFE is a plain call, so its this is undefined in strict mode and globalThis in sloppy mode. An arrow IIFE takes this from the surrounding code.
const widget = {
name: 'widget',
init() {
(function () {
'use strict';
console.log(this); // undefined
})();
(() => {
console.log(this.name); // widget
})();
}
};
widget.init();Async IIFEs
await only works inside an async function, or at the top level of an ES module. In CommonJS scripts, and anywhere else top-level await is not available, an async IIFE gives you an async context:
(async () => {
const value = await Promise.resolve(42);
console.log(value); // 42
})().catch(error => {
console.error('Startup failed:', error);
});The IIFE returns a promise. If nothing handles a rejection, Node.js reports an unhandled rejection, and recent versions exit the process because of it. Attaching .catch to the returned promise is the reliable way to handle errors.
Named IIFEs
An IIFE can be a named function expression. As covered in the named function expression chapter, the name is visible only inside the function, so you can use it for recursion and it shows up in stack traces.
const fib10 = (function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
})(10);
console.log(fib10); // 55
console.log(typeof fib); // "undefined"The Semicolon Trap
If the line before an IIFE has no semicolon, automatic semicolon insertion (ASI) may not add one. The parser then treats the opening parenthesis as a call on the previous expression.
try {
const greeting = 'hi'
(function () {
console.log('never runs');
})()
} catch (error) {
console.log(error instanceof TypeError); // true: "hi" is not a function
}The engine reads this as 'hi'(function () {...})(). Codebases that skip semicolons usually start an IIFE line with a defensive ;, as in ;(function () {})(). A linter rule such as ESLint's no-unexpected-multiline catches this mistake.
IIFEs Compared With Modern Alternatives
| Need | IIFE | Modern alternative | Prefer |
|---|---|---|---|
| Keep temporary variables out of the outer scope | `(function () { ... })()` | A bare block `{ let x = ...; }` | Block |
| Private state behind a public API | Module pattern | ES module with selective `export`, or class `#private` fields | ES module |
| Per-iteration value in a loop | IIFE with a parameter | `let` in the `for` header | `let` |
| `await` outside an async function | Async IIFE | Top-level `await` in an ES module | Top-level `await` where supported |
| Compute a `const` from several statements | `const x = (() => { ... })();` | A named helper function | Either; IIFE keeps the logic next to its only use |
| Isolate a script that runs in a shared global scope | Wrap the whole file | `<script type="module">` | Module, if you control the loading |
The const initializer case is still a legitimate modern use. It lets you build a value with several statements, such as if/else or try/catch, and still declare the result with const:
const port = (() => {
const raw = Number(process.env.PORT);
if (Number.isInteger(raw) && raw > 0) {
return raw;
}
return 3000;
})();
console.log(port); // 3000 unless PORT is set to a positive integerExercises
Exercise
Why does function () { return 1; }(); throw a SyntaxError, while (function () { return 1; })(); runs? Give two other ways to make the first version run without wrapping it in parentheses.
Show answer
A statement that starts with the function keyword is parsed as a function declaration. Declarations need a name and cannot be called in place. Wrapping the function in parentheses makes the parser read it as an expression, which can be called. Other ways to force expression position are a unary operator (!function () { return 1; }(); or void function () { return 1; }();) or placing it on the right side of an assignment (const x = function () { return 1; }();).
Exercise
What does this code log, and why? var out = []; for (var i = 0; i < 2; i++) { (() => { out.push(() => i); })(); } console.log(out.map(f => f()));
Show answer
It logs [ 2, 2 ]. The arrow IIFE creates a new scope, but it takes no parameter, so it never copies i. Every closure still refers to the single function-scoped var i, which is 2 when the loop ends. To fix it, pass i in as an argument, ((n) => { out.push(() => n); })(i);, or declare the loop variable with let.
Exercise
A file without semicolons contains const total = compute() on one line and (async () => { await save(total) })() on the next. What goes wrong, and how do you fix it?
Show answer
ASI does not insert a semicolon after compute() because the next line starts with (. The code becomes compute()(async () => {...})(), which calls the return value of compute() as a function. That usually throws a TypeError. Fix it by adding a semicolon at the end of the first line or by starting the IIFE line with ;. Also attach .catch to the async IIFE so a rejection from save is handled.