Full answer
An IIFE is a function expression that is called immediately. The extra parentheses turn a function declaration into an expression: (function () { ... })(); or with an arrow function, (() => { ... })();. A statement that starts with the word function is read as a declaration and needs a name, so the parentheses (or an operator such as ! or void in front) force expression parsing.
Why it was used: before let, const, and modules, the only scopes were the function and the global scope. Every top-level var became a property of the global object, and scripts from different files collided. An IIFE wrapped a file or a feature in its own scope. It also created private state: a returned object exposed a public API while the variables stayed hidden in the closure (the module pattern). It also captured the loop variable for each iteration in var loops: (function (i) { ... })(i).
Today:
- ES modules give every file its own scope, so file-level IIFEs are not needed.
letandconstare block scoped, so a plain block{ ... }creates a private scope for temporary variables.- Loop variables declared with
letare per iteration.
Where IIFEs still make sense:
- Initialization that needs several statements to produce a single constant:
const config = (() => { ...; return value; })();. - Running
awaitin a script that is not a module:(async () => { ... })();. Handle errors with.catch, because an unhandled rejection can otherwise be lost. - Scripts that must not touch the global scope, such as bookmarklets, snippets injected into pages, and legacy bundles.
- Making private state in a quick factory without a class.
Remember that the function runs once, and that an IIFE has its own this (a normal function) or the outer this (an arrow function).
// classic IIFE with private state
const counter = (function () {
let count = 0;
return {
increment: () => ++count,
get value() { return count; },
};
})();
counter.increment();
counter.increment();
console.log(counter.value, typeof count);
// ways to force expression parsing
(function () { console.log('wrapped in parentheses'); })();
(() => console.log('arrow IIFE'))();
!function () { console.log('with a leading operator'); }();
void function () { console.log('with void'); }();
try {
new Function('function () { }();');
} catch (error) {
console.log('a bare function declaration call:', error.name);
}
// a constant computed by several statements
const settings = (() => {
const base = { retries: 3 };
const fromEnv = Number('2');
return { ...base, retries: Number.isNaN(fromEnv) ? base.retries : fromEnv };
})();
console.log(settings);
// the old fix for var in loops
var oldStyle = [];
for (var i = 0; i < 3; i++) {
(function (copy) { oldStyle.push(() => copy); })(i);
}
const withVar = [];
for (var j = 0; j < 3; j++) withVar.push(() => j);
console.log(oldStyle.map((fn) => fn()), withVar.map((fn) => fn()));
// let does the same without an IIFE
const withLet = [];
for (let k = 0; k < 3; k++) withLet.push(() => k);
console.log(withLet.map((fn) => fn()));
// async IIFE
(async () => {
const value = await Promise.resolve('async result');
console.log(value);
})().catch((error) => console.error(error));
console.log((function () { return typeof this; }).call('text'), (() => typeof this)());Run with Node.js v24.22.1 as js-157.js; two runs gave identical output. Output: 2 undefined wrapped in parentheses arrow IIFE with a leading operator with void a bare function declaration call: SyntaxError { retries: 2 } [ 0, 1, 2 ] [ 3, 3, 3 ] [ 0, 1, 2 ] object object async result
Key points
- An IIFE defines and calls a function at once; parentheses make it an expression.
- It created private scope and the module pattern before let, const, and modules.
- Modules and block scope replaced most uses.
- Still useful for one-off initialization, async code in non-module scripts, and scripts that avoid globals.
- Handle errors of async IIFEs; this differs between function and arrow forms.
Common mistakes
- Forgetting the semicolon before an IIFE that starts with a parenthesis, which joins it with the previous line.
- Using file-level IIFEs inside ES modules, where they add nothing.
- Leaving an async IIFE without error handling.
- Expecting this inside an arrow IIFE to be a new object.
Follow-ups
- Why does a function declaration followed by () give a syntax error?
- How did the module pattern work before ES modules?
- When is a plain block with let better than an IIFE?
Tips
- Explain why the parentheses are needed.
- Say that modules and let replaced most uses, and name the cases where an IIFE still helps.
- Mention error handling for async IIFEs.