Learn JavaScript
❯ functions.iife

IIFEs & the Module Pattern in JavaScript

$concept

An IIFE (Immediately Invoked Function Expression) defines and runs a function in one expression — (function() { ... })() — creating a private scope before block-scoped let and ES modules existed. Libraries wrapped entire codebases in IIFEs to avoid global collisions, exposing chosen APIs through a returned object (the module pattern).

Modern code reaches for real modules instead, but IIFEs survive in legacy code, bookmarklets, one-off scripts, and async contexts ((async () => { await ... })() as top-level-await polyfill). Recognize the shape instantly; write modules for new isolation needs.

$how it works
1

Define and run at once

(function() { ... })() — the wrapping parens make it an expression, the trailing () invokes immediately.

2

Private scope, public API

const M = (function() { let secret = 1; return { get: () => secret }; })(); — hidden state plus exposed methods.

3

Async variant

(async () => { await setup(); })(); runs async setup where top-level await is unavailable.

4

Modules supersede

ES modules provide file scope natively — IIFEs remain for legacy reading, snippets, and constrained contexts.

$example
const counter = (function() {
let n = 0;
return { next: () => ++n };
})();
console.log(counter.next(), counter.next());
Output
1 2
1The IIFE runs once, creating private n and returning an object with a next method closing over it.
2counter.next() increments the hidden n — 1, then 2.
3n is unreachable except through next — module-pattern privacy without classes.
$use cases
Reading pre-module libraries wrapped in IIFE scopes
One-off scoped scripts avoiding global leakage
Async setup blocks where top-level await is unavailable
Module pattern privacy in environments without ES modules

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.