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 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.
const secret = "private"; // ← not accessible outside
console.log(secret); // ← runs immediately
})();
( ) — 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
// 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
( ), 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:
const x = 1;
})();
() is inside the outer parens.
Most common style.const x = 1;
}());
() is inside the outer parens.
Both styles are equally valid.const x = 1;
})();
this.const data = await fetch();
})();
async wrapper
function.// internal name for recursion
})();
// return value discarded
}();
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:
window / global scope.let, IIFEs inside loops captured the loop
variable correctly by creating a new scope per iteration.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:
// ── 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); // trueScope 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:
// ── 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:
var
var
let / const are
block-scoped — { } is enough
type="module") have
their own scope by default
let i in for loops is already
scoped per iteration
// ── 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 };
})();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 |
Try It — Live Editor
Experiment with IIFEs below. Try passing different arguments, capturing the return value, or building your own Revealing Module pattern.
Common Patterns & Recipes
These are the real-world IIFE patterns you'll encounter in production codebases, jQuery plugins, and legacy JavaScript libraries:
// ── 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( ) required in an IIFE?- 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
awaitis not available natively.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.