Immediately Invoked Functions (IIFE)
Immediately Invoked Function Expressions (IIFE)
An IIFE (pronounced "iffy", Immediately Invoked Function Expression) is a JavaScript design pattern where a function runs immediately as soon as it is defined.
1. Syntax of an IIFE
An IIFE is composed of two primary parts:
- 1The Grouping Operator
(...): Wraps the function declaration, instructing the JavaScript parser to treat it as an expression rather than a statement. - 2The Invocation Operator
(): Immediately calls the function expression.
Modern Arrow Function IIFE Syntax:
2. Why Did Developers Use IIFEs? (Legacy Context)
Before ES6 introduced let, const, and ES Modules, all variables declared with var were globally scoped unless inside a function. If you included multiple script files on a web page:
The Solution: The IIFE Sandbox Pattern
By wrapping each file inside an IIFE, developers created a private function scope, completely protecting the global window namespace from variable collisions:
3. Modern Use Cases for IIFEs
While ES Modules (import/export) have largely superseded IIFEs for namespace isolation, IIFEs are still widely used in modern JavaScript for:
A. Top-Level async Execution in Older Environments:
B. Creating Module Singletons:
Practice Quiz
(function() { ... })?querySelectorAll & forEach
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Closures Introduction | querySelectorAll & forEach |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.