What is an IIFE (Immediately Invoked Function Expression)?
Answer
An IIFE (Immediately Invoked Function Expression) is a function that is defined and called immediately. Syntax: (function() { /* code */ })() or (() => { /* code */ })(). The outer parentheses turn the function declaration into an expression; the trailing () immediately invokes it. Primary use: creating a private scope — variables inside an IIFE do not pollute the global scope (pre-ES6 when there were no block-scoped variables). This was the basis of the module pattern: const counter = (function() { let count = 0; return { inc: () => ++count, get: () => count }; })(). IIFEs are also used to avoid variable hoisting issues in loops. With ES6 let/const and modules, IIFEs are less necessary, but still used for: executing top-level async code ((async () => { const data = await fetch(url); })();), avoiding variable naming conflicts in scripts, and wrapping legacy code.
Previous
What is function composition in JavaScript?
Next
What is the arguments object in JavaScript?