Immediately Invoked Functions (IIFE)0%

Immediately Invoked Functions (IIFE)

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

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:

  1. 1
    The Grouping Operator (...): Wraps the function declaration, instructing the JavaScript parser to treat it as an expression rather than a statement.
  2. 2
    The Invocation Operator (): Immediately calls the function expression.
JavaScript
(function() {
console.log("I run immediately upon declaration!");
})();

Modern Arrow Function IIFE Syntax:

JavaScript
(() => {
console.log("Arrow function IIFE executed!");
})();

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:

JavaScript
// file1.js
var count = 0;
 
// file2.js
var count = 100; // 💥 OOPS! file2 silently overwritten file1's global variable!

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:

JavaScript
// file1.js
(function() {
var count = 0; // Private! Cannot collide with file2!
})();
 
// file2.js
(function() {
var count = 100; // Private!
})();

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:

JavaScript
(async () => {
try {
const res = await fetch("https://api.github.com/users/sumit-msk");
const data = await res.json();
console.log("User:", data.name);
} catch (err) {
console.error("Fetch failed:", err);
}
})();

B. Creating Module Singletons:

JavaScript
const DatabaseConnection = (() => {
let instance = null;
 
function createInstance() {
return { connectionId: Math.random() };
}
 
return {
getInstance() {
if (!instance) instance = createInstance();
return instance;
}
};
})();
 
console.log(DatabaseConnection.getInstance().connectionId);

Interactive Quiz

Practice Quiz

Question 1
What does IIFE stand for?
Question 2
What is the purpose of wrapping the function in parentheses (function() { ... })?
Question 3
Historically, what was the primary motivation for using the IIFE pattern?
Question 4
How is an arrow function written as an IIFE?
Question 5
Can arguments be passed into an IIFE?
Next Lesson

querySelectorAll & forEach

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext