Intermediate JavaScript Interview QuestionsIntermediateConcept
JavaScript · Question 44
What is an IIFE in JavaScript, and why was it historically common?
Direct answer
An IIFE is a function expression invoked immediately after it is created; it was widely used to create private function scope and avoid global variables before block scope and ES modules became standard.
A typical form is (function(){ const privateValue = 1; })(); or the arrow equivalent (() => { /* setup */ })();. The surrounding parentheses force the parser to treat the function as an expression, and the final parentheses invoke it.
- Older browser code used IIFEs to isolate variables because
varis function-scoped and script files otherwise shared globals. - The module pattern used IIFEs plus closures to expose a small public API while keeping implementation details private.
- Today,
let,const, block scope, and ES modules remove many historical reasons for IIFEs. - Async IIFEs can still be useful when an immediate async execution wrapper is convenient in a context that cannot use top-level await.