Immediately Invoked Function Expression
JavaScript IIFE
An IIFE (Immediately Invoked Function Expression) is a function that runs immediately after it is defined.
IIFEs where often used for encapsulation, especially before ES6 modules existed.
Self-Invoking Functions
Function expressions can be made self-invoking.
A self-invoking expression is invoked (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 in parentheses to turn it into an expression.
- 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
(function () {
let hidden = 42;
})();
let result = hideen; // ⛔ Error: hidden is not defined
Simple IIFE
The function above is also called an anonymous self-invoking function (function without name).
IIFE with Parameters
Arrow Function IIFE
Arrow Function IIFE with Parameter
IIFE as a Module (Private Variables)
Example
const counter = (function () {
let value = 0;
return {
increment() { value++; },
get() { return value; }
};
})();
counter.increment();
let x = counter.get();
Try it Yourself »
Named Function Expression IIFE
You can give an IIFE a name:
Example
(function greet() {
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
(function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1); // recursive call
})(5);
Notes
IIFEs were heavily used before ES6 introduced let, const, and Modules.
They are still useful for:
- Running setup code
- Creating private variables
- Avoiding global scope pollution