immediately invoked function expression (IIFE)
An immediately invoked function expression (IIFE) is a function expression that JavaScript calls at the same spot where the code defines it, so its body runs once, right away.
The usual form wraps a function or an arrow function in parentheses and follows it with a call, as in (() => { ... })(). The parentheses make the parser read the function as an expression. A statement that starts with the function keyword parses as a function declaration instead, which can’t be called in place.
Each call creates a new function scope, so the variables an IIFE declares stay inside it. Before let, const, and ES modules, browser scripts used IIFEs to keep their variables out of the shared global scope. Today IIFEs show up in bundler output, in older libraries, and as async IIFEs that allow await in code without top-level await, such as CommonJS modules.
Example
Say a page script needs a click counter whose count no other script can change. An IIFE runs once, keeps count in its own scope, and returns an object whose method updates it:
> const counter = (() => {
… let count = 0;
… return {
… increment() {
… count += 1;
… return count;
… },
… };
… })();
undefined
> counter.increment()
1
> counter.increment()
2
> typeof count
'undefined'
The counter binding holds the returned object, not the function. Its increment() method forms a closure over count, which outside code can’t reach, so typeof count reports 'undefined'.
An IIFE that starts a line can also join the line above it. Without a semicolon after the first statement, JavaScript reads the opening parenthesis as a call on the previous value:
report.mjs
const title = "Monthly report"
(() => {
console.log("Setting up the report");
})();
Running the module fails before the IIFE’s body runs:
$ node report.mjs
TypeError: "Monthly report" is not a function
Automatic semicolon insertion doesn’t add a semicolon here, because the two lines form a valid call expression. Ending the first statement with a semicolon fixes the program.
Related Resources
Course
JavaScript Scope, Closures, and Functional Patterns for Pythonistas
Port a bouldering gym's front-desk script to JavaScript, and learn where names live and when they exist, how closures keep state, and how to work with rest parameters, callbacks, and timers.
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 15, 2026