All topics
Fundamentalsbeginner

Immediately Invoked Function Expressions Basics

A function that runs the instant it's defined, historically used to create private scope before block-scoping and modules existed.

An IIFE (Immediately Invoked Function Expression) is a function that is defined and executed in the same statement, and while it's less central to modern code than it once was, understanding why it existed is a strong signal that you understand JavaScript's scoping history. It's still commonly seen in older codebases, bundler output, and certain module patterns.

An IIFE is like unwrapping a candy, eating it immediately, and throwing away the wrapper in one motion — nothing about that candy lingers around for anyone else to grab afterward, except whatever taste (return value or closure) you deliberately kept.

Key Concepts

1
The syntax wraps a function expression in parentheses and immediately calls it: (function() { ... })(). Wrapping the function in parentheses is necessary because the function keyword at the start of a statement is parsed as a function declaration, which cannot be immediately invoked; wrapping it in parentheses forces the parser to treat it as an expression instead. Arrow function IIFEs follow the same pattern: (() => { ... })().
(function() { ... })()function(() => { ... })()
2
Before ES6 introduced block scoping with let/const and native modules, IIFEs were the primary tool for creating a private, isolated scope — variables declared inside only existed within that function and could not leak into the global scope or collide with other scripts on the page. This was especially important for library authors shipping code that would run alongside other unrelated scripts, since global namespace pollution was a real, common problem.
letconst
3
Today, ES modules provide file-level scoping automatically, and let/const provide block scoping, so IIFEs are needed far less often for basic isolation. They still appear in bundler-generated code (to wrap each module in its own scope) and in patterns like the module pattern, where an IIFE returns an object exposing only specific public methods while keeping other variables private via closure.
letconst