JavaScript Interview Question #103
What is an IIFE in JavaScript?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
An IIFE, or Immediately Invoked Function Expression, is a function expression that executes immediately after it is created. Before ES modules and block-scoped declarations became common, IIFEs were frequently used to create a private scope and avoid leaking variables into the global scope.
Detailed Explanation
An IIFE, or Immediately Invoked Function Expression, is a function expression that executes immediately after it is created. Before ES modules and block-scoped declarations became common, IIFEs were frequently used to create a private scope and avoid leaking variables into the global scope.
IIFEs still appear in existing code and can be useful for one-time initialization, although modules and block scope now solve many of the same organizational problems more directly.
Code Example
(function () {
const message = "Initialized privately";
console.log(message);
})();
(() => {
console.log("Arrow-function IIFE");
})();