An IIFE (pronounced "iffy", Immediately Invoked Function Expression) is a JavaScript design pattern where a function runs immediately as soon as it is defined.
1. Syntax of an IIFE
An IIFE is composed of two primary parts:
1
The Grouping Operator (...): Wraps the function declaration, instructing the JavaScript parser to treat it as an expression rather than a statement.
2
The Invocation Operator (): Immediately calls the function expression.
1(function(){
2 console.log("I run immediately upon declaration!");
3})();
Modern Arrow Function IIFE Syntax:
1(()=>{
2 console.log("Arrow function IIFE executed!");
3})();
2. Why Did Developers Use IIFEs? (Legacy Context)
Before ES6 introduced let, const, and ES Modules, all variables declared with var were globally scoped unless inside a function. If you included multiple script files on a web page:
By wrapping each file inside an IIFE, developers created a private function scope, completely protecting the global window namespace from variable collisions:
1// file1.js
2(function(){
3var count =0;// Private! Cannot collide with file2!
4})();
5
6// file2.js
7(function(){
8var count =100;// Private!
9})();
3. Modern Use Cases for IIFEs
While ES Modules (import/export) have largely superseded IIFEs for namespace isolation, IIFEs are still widely used in modern JavaScript for:
A. Top-Level async Execution in Older Environments:
1(async()=>{
2try{
3const res =awaitfetch("https://api.github.com/users/sumit-msk");