Immediately Invoked Expression
JavaScript IIFE
AnIIFE (Immediately Invoked Function Expression) is a function that runsimmediately after it is defined.
IIFEs where often used for encapsulation, especiallybefore ES6 modules existed.
Self-Invoking Functions
Function expressions can be madeself-invoking.
A self-invoking expression isinvoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().
You have to add parentheses around the function to indicate that it is an expression:
Syntax
(function () { // Code to run immediately})();- The function is wrapped inparentheses to turn it into anexpression.
- The final() executes the function immediately.
Note
You can only self-invoke a function expression.
You can not self-invoke a function declaration.
When Use an IIFE?
Although ES6 let, const, and modules reduce the need for IIFEs, they are still useful when:
- You want private scope in a browser script file
- You need initialization code that should run immediately
- Working with older code that rely on them
Avoid Polluting the Global Scope
Variables inside an IIFE cannot be accessed from outside.
Example
let hidden = 42;
})();
let result = hideen; // ⛔ Error: hidden is not defined
Simple IIFE
The function above is also called ananonymous self-invoking function (function without name).
IIFE with Parameters
Arrow Function IIFE
Arrow Function IIFE with Parameter
IIFE as a Module (Private Variables)
Example
let value = 0;
return {
increment() { value++; },
get() { return value; }
};
})();
counter.increment();
let x = counter.get();
Named Function Expression IIFE
You can give an IIFE a name:
Example
let text = "Hello! I called myself.";
})();
greet(); // ⛔ ReferenceError
But, the name greet exists only inside the function itself, not in the outer/global scope.
Why use a named IIFE?
For self-recursion functions (calling itself repeatedly):
Example
if (n <= 1) return 1;
return n * factorial(n - 1); // recursive call
})(5);
Notes
IIFEs were heavily used before ES6 introducedlet,const, andModules.
They are still useful for:
- Running setup code
- Creating private variables
- Avoiding global scope pollution

