IIFEs and the Module Pattern
The IIFE, and the pre-ES6 trick of pairing one with closures to fake private state and a public API — what people did before real modules existed.
Function Declarations, Expressions, and Arrow FunctionsClosures
IIFEs and the Module Pattern
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An IIFE (Immediately Invoked Function Expression) is a function defined and called in the same statement — wrapping it in parentheses forces the parser to treat it as an expression, which is what lets `()` immediately after it actually invoke it instead of causing a syntax error.
- Before ES6 modules existed, every `<script>` tag on a page shared one global scope — any variable declared at the top level of one file was visible to, and could collide with, every other script on the page.
- An IIFE runs in its own function scope the instant it's defined, so anything declared inside it never leaks into the global scope at all — this was the main tool for avoiding global namespace collisions before real module scoping existed.
- The module pattern layers closures on top of an IIFE: the IIFE's private variables and functions stay hidden by normal scoping, and the object it returns exposes only the specific methods you choose, each one keeping access to that private state through closure — a public API over a fake-private implementation, assembled from mechanisms that already existed.
- ES modules made this entire pattern a workaround for a problem that no longer exists: every module file already has its own private scope by default, and `export` replaces manually building and returning an object, which is why you'll mostly meet IIFEs and the module pattern now in older code, not new code.
The problem that existed before modules did
Picture a web page loading several <script> tags before ES6 modules
existed: a date-formatting helper, a form-validation library, your own
application code. All of them ran in the same global scope. A var
declared at the top level of any one file wasn’t local to that file — it
became, effectively, a property on the shared global object, visible to
and overwritable by every other script on the page. Two unrelated files
both using the name count or init weren’t an unlikely coincidence;
with enough scripts on a page, name collisions were close to guaranteed,
and whichever script happened to run last would silently overwrite
whatever the others had set up.
JavaScript at the time had no concept of a file having its own private scope. The fix people reached for used two features that already existed — function scope, and closures — combined into a pattern.
IIFEs: a function born already running
An Immediately Invoked Function Expression is exactly what its name says: a function that gets defined and called in the same statement, so it runs once, immediately, and is gone.
(function () {
var secret = "nobody outside can see this";
console.log("running immediately");
})();
The parentheses around the function aren’t decoration — they’re load-bearing.
A statement that starts with the keyword function is parsed as a
function declaration, which requires a name and can’t be called inline
the way this needs to be. Wrapping it in (...) forces the parser to read
it as a function expression instead — a value, which can be immediately
followed by () to call it, the same as calling any function stored in a
variable.
The reason this solved the global-scope problem: anything declared inside
that function — secret, in the example above — lives in the function’s
own scope. It never touches the global scope at all, so it can’t collide
with anything declared inside a different script’s own IIFE, no matter
how many of them are loaded on the same page.
The module pattern: IIFE plus closures equals a fake-private API
An IIFE on its own just hides things — it’s not very useful if nothing inside it can ever be reached from outside. The module pattern adds one more step: instead of doing work and discarding everything, the IIFE returns an object, and that object’s methods are closures that still have access to the IIFE’s private variables.
const Counter = (function () {
let count = 0; // private — unreachable from outside
function increment() {
count += 1;
return count;
}
function reset() {
count = 0;
}
return { increment, reset }; // public API
})();
Counter.increment(); // 1
Counter.increment(); // 2
Counter.count; // undefined — there's no such public property
count is never exposed directly — there’s no way to reach in and set it
from outside. increment and reset are the only sanctioned doors in and
out, and they work because each one is a closure created inside the same
scope count lives in, exactly like the closures covered in the previous
two lessons. The result looks and behaves like an object with private
state and a public API, built entirely out of function scope and
closures — no private keyword, no class, no language feature designed
for this specific purpose, because none existed yet.
Why this stopped being necessary
ES modules (covered later in this roadmap) give every file a private
scope by default — nothing declared in one module file leaks into another
unless it’s explicitly exported. That’s precisely the problem the IIFE
half of this pattern existed to solve, now handled automatically by the
module system itself. And export lets a module name its public surface
directly, which is what manually constructing and returning an object
from inside an IIFE was standing in for. The module pattern wasn’t wrong
— it was a correct solution assembled from the tools available at the
time. You’ll still run into it constantly in legacy code and inside the
output bundlers produce, which is exactly why it’s worth understanding on
its own terms rather than skipping straight to modules.
Where this fits
This lesson closes out the “Functions and this” group by tying
function expressions
and closures together into something
genuinely historical: the direct ancestor of
ES modules, taught
later in this roadmap. Seeing why modules were needed before meeting
the feature that replaced this pattern makes that later lesson land as an
obvious improvement rather than an arbitrary new syntax to memorize.
Check yourself
Why does `(function () { ... })()` need the outer parentheses — what goes wrong if you write `function () { ... }()` instead?
A statement starting with the `function` keyword is parsed as a function declaration, and a function declaration needs a name and can't be immediately called with a trailing `()` — that's a syntax error. Wrapping it in parentheses forces the parser to treat it as a function *expression* instead, which is a value that can be called immediately, the same way any other expression producing a function could be.
Before ES6 modules, why did declaring `var count = 0;` at the top level of one `<script>` file risk breaking a completely different script on the same page?
Every script on a page ran in one shared global scope, so a top-level `var` in one file created a property on the same global object every other script could see and overwrite. A second, unrelated script declaring its own `count` wasn't creating a separate variable — it was silently colliding with the first one, and whichever ran last would stomp on the other's value.
How does wrapping code in an IIFE prevent that kind of global collision?
Anything declared inside a function — IIFE included — lives in that function's own scope, not the global one. Because the IIFE runs immediately and its body never leaks a bare `var`/`let`/`const` out into the surrounding scope, whatever it declares internally simply isn't visible to, or collidable with, any other script on the page.
In the module pattern, what makes a variable declared inside the IIFE "private," and what makes a method on the returned object "public"?
The private variable is simply a normal local variable inside the IIFE's function body — ordinary scoping already makes it unreachable from outside. The "public" methods are properties on the object the IIFE returns; each one is a closure that was defined inside the same scope as the private variable, so it keeps access to it, while code outside the module can only reach that variable through whichever public method chooses to expose it.
Why don't modern codebases need the IIFE-plus-module-pattern trick anymore?
ES modules give every file its own private scope automatically — nothing declared in a module leaks to any other file by default, which is the exact problem the IIFE half of the pattern existed to solve. And `export` lets a module expose specific names directly, which is what manually building and returning an object from inside an IIFE was standing in for. The underlying goal — scope isolation plus a chosen public surface — is now a built-in language feature instead of a pattern you had to assemble by hand.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.