IIFEs & the Module Pattern in JavaScript
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.
Define and run at once
(function() { ... })() — the wrapping parens make it an expression, the trailing () invokes immediately.
Private scope, public API
const M = (function() { let secret = 1; return { get: () => secret }; })(); — hidden state plus exposed methods.
Async variant
(async () => { await setup(); })(); runs async setup where top-level await is unavailable.
Modules supersede
ES modules provide file scope natively — IIFEs remain for legacy reading, snippets, and constrained contexts.
const counter = (function() { let n = 0; return { next: () => ++n };})();console.log(counter.next(), counter.next());Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.