Ch 29 / 78
Chapter 29 Intermediate 6 min read JavaScript

IIFE — Immediately Invoked Function Expression

An IIFE is a function that defines itself and calls itself in the same expression. It was the cornerstone of the pre-ES6 module pattern — creating private scopes and protecting variables from polluting the global namespace. Even in modern JS it remains a clean, intentional tool for one-off initialisation and scope isolation.

What you'll learn
What IIFE stands for and its core syntax
Why the outer parentheses are required
All IIFE syntax variants — classic, arrow, async
Scope isolation and private variables
Passing arguments and capturing return values
IIFE vs block scope — when to use each today

What is an IIFE?

IIFE stands for Immediately Invoked Function Expression. It is a function that is defined and called at the same time, in a single expression. The variables declared inside it stay private — completely hidden from the outer scope — and the function itself is discarded immediately after running.

(function() {
  const secret = "private";  // ← not accessible outside
  console.log(secret);  // ← runs immediately
})();
Outer ( ) — wraps function, turns declaration into expression function() — anonymous function expression inside Body — runs immediately; all vars stay private Trailing () — the invocation call; runs the function instantly Semicolon — terminates the whole expression statement
JavaScript — First IIFE
// The function runs immediately — no separate call needed
(function() {
console.log("I run immediately!");
})();
// Output: "I run immediately!"

// Variables inside are completely private
(function() {
const privateVar = "hidden";
console.log(privateVar); // "hidden" — accessible inside
})();

// console.log(privateVar); // ❌ ReferenceError — not accessible here

// Without the outer parentheses — SyntaxError!
// function() { }(); // ❌ JS expects a name after 'function' in statement position
Why the outer parentheses?
Without the outer ( ), the JavaScript parser sees function at the start of a statement and expects a function declaration with a name. The outer parentheses turn it into an expression, which can be immediately followed by () to invoke it. Any operator that forces expression context works — !, +, void, or =.

IIFE Syntax Variants

There are several valid ways to write an IIFE. They all produce the same result — the differences are style and readability preferences:

Classic (Crockford Style)
(function() {
  const x = 1;
})();
Invocation () is inside the outer parens. Most common style.
Alternative (Douglas Style)
(function() {
  const x = 1;
}());
Invocation () is inside the outer parens. Both styles are equally valid.
Arrow Function IIFE (ES6)
(() => {
  const x = 1;
})();
Concise and modern. Note: arrow IIFEs do not bind their own this.
Async IIFE (ES2017)
(async () => {
  const data = await fetch();
})();
Run top-level async code without a named async wrapper function.
Named IIFE
(function init() {
  // internal name for recursion
})();
Giving the IIFE a name improves stack traces and allows internal recursion.
Unary Operator Trick
void function() {
  // return value discarded
}();
The void, !, +, or ~ operator forces expression context. Rarely seen today.

Why Use an IIFE?

Before ES6 introduced let, const, and native modules, IIFEs were the only reliable way to create private scope in JavaScript. They remain useful today for several specific scenarios:

Scope Isolation
Variables inside an IIFE cannot be read or overwritten from outside. No accidental global pollution.
Avoid Global Pollution
Wrapping a script in an IIFE prevents helper variables from leaking into window / global scope.
One-Time Initialisation
Run setup code exactly once, immediately — no need to name the function and then call it on the next line.
Module / Namespace Pattern
Return an object from an IIFE to expose a clean public API while keeping implementation details hidden.
Closure Loop Fix (pre-ES6)
Before let, IIFEs inside loops captured the loop variable correctly by creating a new scope per iteration.
Top-Level Async
An async IIFE lets you use await at the "top level" of a script without needing a named async function.

Passing Arguments & Capturing Return Values

IIFEs can accept arguments (passed in the invocation parentheses) and return values that can be stored in a variable — giving you the full power of a function in a self-contained expression:

JavaScript — IIFE Arguments & Return
// ── Passing arguments to an IIFE ─────────────────────────────
(function(name, age) {
console.log(`Hello, ${name}! You are ${age} years old.`);
})("Priya", 25); // ← args passed at invocation
// "Hello, Priya! You are 25 years old."

// ── Capturing return value ────────────────────────────────────
const result = (function(x, y) {
return x * y;
})(6, 7);
console.log(result); // 42

// ── Classic global aliasing pattern ──────────────────────────
// Pass window/document/$ to avoid long property lookups
(function(win, doc, $) {
// Use win, doc, $ as local aliases — faster & safer
console.log(win === window); // true
})(window, document, jQuery);

// ── IIFE returning a configuration object ────────────────────
const config = (function() {
const env = "production"; // private
const version = "2.1.0"; // private
return {
isProduction: env === "production",
version,
apiBase: env === "production" ? "https://api.k2.com" : "http://localhost:3000"
};
})();
console.log(config.version); // "2.1.0"
console.log(config.isProduction); // true

Scope Isolation in Practice

The core power of an IIFE is its ability to create a completely private scope. Any variable declared inside cannot be read, written, or accidentally overwritten by code outside — even if an outer variable has the same name:

JavaScript — Scope Isolation
// ── Two scripts on the same page — no conflicts ──────────────
// script-a.js
(function() {
var count = 0; // private to this IIFE
console.log("Script A count:", count);
})();

// script-b.js
(function() {
var count = 99; // completely separate — no collision!
console.log("Script B count:", count);
})();

// console.log(count); // ❌ ReferenceError — neither is global

// ── The Revealing Module pattern ─────────────────────────────
const CartModule = (function() {
// Private state
let items = [];
let discount = 0;

// Private helper
function calcTotal() {
return items.reduce((s, item) => s + item.price, 0) * (1 - discount);
}

// Public API — only these are accessible outside
return {
addItem(item) { items.push(item); },
setDiscount(d) { discount = d; },
total() { return calcTotal(); },
itemCount() { return items.length; }
};
})();

CartModule.addItem({ name: "Book", price: 200 });
CartModule.addItem({ name: "Pen", price: 50 });
CartModule.setDiscount(0.1); // 10% off
console.log(CartModule.total()); // 225
console.log(CartModule.itemCount()); // 2
// console.log(CartModule.items); // undefined — private!

IIFE vs Block Scope — Modern Comparison

With ES6's let, const, and native ES Modules, many historical uses of IIFEs can be replaced by simpler syntax. Here's when to use each:

IIFE — ES5 era approach
Required to create private scope with var
Used to simulate modules before ES Modules existed
Fixed loop closure bugs caused by var
Still valid for Revealing Module pattern in non-module scripts
Block Scope — ES6+ approach
let / const are block-scoped — { } is enough
ES Modules (type="module") have their own scope by default
let i in for loops is already scoped per iteration
Still use IIFE for async top-level and one-off init
JavaScript — IIFE vs Block Scope
// ── Scope isolation: IIFE vs Block ───────────────────────────
// Old (IIFE)
(function() {
var temp = "private";
})();

// Modern (Block — much simpler)
{
const temp = "private"; // block-scoped with const/let
}

// ── Loop closure fix: IIFE vs let ────────────────────────────
// Old (IIFE) — creates new scope per iteration
for (var i = 0; i < 3; i++) {
(function(j) {
setTimeout(() => console.log(j), 100);
})(i);
} // 0 1 2 ✓

// Modern (let — block-scoped per iteration)
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
} // 0 1 2 ✓ (no IIFE needed)

// ── Where IIFE is still the best tool ────────────────────────
// 1. Async top-level (without top-level await support)
(async () => {
const data = await fetch("/api/init").then(r => r.json());
console.log(data);
})();

// 2. Revealing Module pattern (non-module scripts)
const App = (function() {
let _version = "1.0.0";
return { getVersion: () => _version };
})();
Tip
If you're writing modern ES6+ code with let/const and ES Modules, you rarely need an IIFE for scope isolation. But async IIFEs are still widely used — and knowing the pattern is essential for reading older codebases, jQuery plugins, and library source code.

IIFE Pattern Reference

A quick reference for all major IIFE forms and when each is used in the wild:

Pattern Era Use Case
(function(){…})() ES5+ Classic scope isolation, avoiding global pollution
(function(){…}()) ES5+ Same as above — alternate bracket placement style
(() => {…})() ES6+ Concise arrow IIFE — no own this binding
(async () => {…})() ES2017+ Top-level await without native top-level await
const X = (function(){…})() ES5+ Revealing Module pattern — capture returned public API
(function(win){…})(window) ES5 Pass globals as local aliases for speed and minification safety
void function(){…}() Legacy Unary operator forces expression context — rarely used today
⚡
Free Resource
Download our JavaScript Cheat Sheet
Functions, closures, IIFEs & module patterns — all on one page.
Get Sheet

Try It — Live Editor

Experiment with IIFEs below. Try passing different arguments, capturing the return value, or building your own Revealing Module pattern.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are the real-world IIFE patterns you'll encounter in production codebases, jQuery plugins, and legacy JavaScript libraries:

JavaScript — IIFE Recipes
// ── 1. Self-contained script wrapper (prevents global leaks) ─
(function(global) {
"use strict";
const VERSION = "1.0.0";
function init() { console.log(`App v${VERSION} ready`); }
global.MyApp = { init, VERSION }; // expose only what's needed
})(window);

// ── 2. Async IIFE — top-level await without native support ────
(async () => {
try {
const res = await fetch("https://api.example.com/data");
const data = await res.json();
console.log(data);
} catch (err) {
console.error("Fetch failed:", err);
}
})();

// ── 3. Conditional singleton ─────────────────────────────────
const Logger = (function() {
const isDev = window.location.hostname === "localhost";
return {
log: (...a) => isDev && console.log("[LOG]", ...a),
warn: (...a) => isDev && console.warn("[WARN]", ...a),
error: (...a) => console.error("[ERR]", ...a) // always log errors
};
})();
Logger.log("Only prints in dev");

// ── 4. One-time feature detection ────────────────────────────
const supports = (function() {
return {
touch: "ontouchstart" in window,
localStorage: (() => {
try { localStorage.setItem("_t", "1"); localStorage.removeItem("_t"); return true; }
catch { return false; }
})(),
webp: (function() {
const el = document.createElement("canvas");
return el.toDataURL("image/webp").startsWith("data:image/webp");
})()
};
})();
console.log(supports.localStorage); // true / false
Quick Check
Why are the outer parentheses ( ) required in an IIFE?
Quick Check
What is the main advantage of the Revealing Module pattern using an IIFE?
Chapter Summary
  • An IIFE (Immediately Invoked Function Expression) is a function that is defined and called in a single expression — it runs once and is then discarded.
  • The outer parentheses ( ) are mandatory — they turn the function keyword into an expression context, allowing immediate invocation.
  • All variables declared inside an IIFE are completely private — unreachable from outside, preventing global namespace pollution.
  • IIFEs can accept arguments (passed at invocation) and return values that are captured by an outer variable.
  • The Revealing Module pattern uses an IIFE to expose a clean public API (as a returned object) while keeping private state hidden inside.
  • With ES6+, many IIFE use cases can be replaced by block scope ({ let/const }) and ES Modules — but async IIFEs remain a widely used modern pattern.
  • Common syntax variants: classic (function(){})(), arrow (()=>{})(), async (async()=>{})(), and named (function name(){})().
  • You will encounter IIFEs in jQuery plugins, UMD bundles, older libraries, and anywhere top-level await is not available natively.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel