Closures & Scopemedium

IIFE & Module Pattern

An Immediately Invoked Function Expression (IIFE) is a function that is defined and called in one expression: (function() { ... })(). It creates a private scope to avoid polluting the global namespace.

Memory anchor

IIFE = a self-destructing message in a spy movie. It runs once, does its job, and its private contents are gone from the outside world forever. The parentheses are the detonator.

Expected depth

IIFEs were the primary tool for encapsulation before ES modules. The module pattern uses an IIFE to return a public API while keeping private state in the closure. The revealing module pattern explicitly lists what is public. Named IIFEs are better for debugging since the name appears in stack traces. Arrow function IIFEs are also valid: (() => { ... })(). In modern code, IIFEs are rarely needed since let/const and ES modules handle scope and encapsulation.

Deep — senior internals

The IIFE pattern predates ES modules and was popularized by jQuery and similar libraries to avoid global variable conflicts. UMD (Universal Module Definition) wrappers use IIFEs with factory functions that detect the environment (CommonJS, AMD, global) and export accordingly. The parentheses wrapping the function are needed to change the parser context from a function statement to an expression — without them, the engine expects a function name and throws a syntax error. Alternatively, prefix operators like ! or void also work: !function(){}(). Modern bundlers still wrap modules in function scopes for isolation in non-ESM output.

🎤Interview-ready answer

An IIFE creates a new function scope immediately on execution, providing private encapsulation without polluting the global scope. It was the foundation of the module pattern in pre-ES6 code. Today, ES modules provide better encapsulation natively, but IIFEs still appear in compiled/bundled output and UMD library wrappers.

Common trap

Forgetting the wrapping parentheses causes a SyntaxError — function() {}() is a statement (function declaration), which can't be immediately invoked. Wrapping in parens or prefixing with ! makes it an expression. Also: IIFEs don't have 'name' by default, making debugging harder — always name your IIFEs: (function myModule() { ... })().

Related concepts