IIFE
IIFE (Immediately Invoked Function Expression)
Section titled “IIFE (Immediately Invoked Function Expression)”Introduction
Section titled “Introduction”An IIFE is a function that runs immediately after being defined. It creates a new scope for variables, preventing them from leaking into the global scope.
Syntax
Section titled “Syntax”(function() { // code runs immediately})();
// Arrow function variant(() => { // code runs immediately})();Why Do We Need This?
Section titled “Why Do We Need This?”Before ES6 modules, IIFEs were the primary way to create private scopes and avoid polluting the global namespace.
Visual Explanation
Section titled “Visual Explanation”flowchart LR A["Function Definition"] --> B["Immediately Invoked"] B --> C["New Scope Created"] C --> D["Variables Are Private"] D --> E["Global Scope Not Polluted"]Examples
Section titled “Examples”// Private scope(function() { const privateVar = 'secret'; console.log(privateVar); // 'secret'})();
console.log(privateVar); // ReferenceError
// Module pattern (pre-ES6)const module = (function() { const private = 'private data'; return { getPrivate: () => private };})();
console.log(module.getPrivate()); // 'private data'Summary
Section titled “Summary”- IIFE runs immediately after definition
- Creates a private scope
- Was essential for module pattern before ES6
- Still useful for isolated code execution