Run Immediately
An IIFE runs as soon as it is defined.
It is useful for creating a private scope.
JavaScript Tutorial
An IIFE is a function expression that runs immediately after it is defined.
It creates a private scope and avoids leaking variables globally.
IIFEs were a popular way to isolate variables before ES modules.
They are still useful in quick scripts and legacy codebases.
(function() { ... })()
(() => { ... })()(function() {
console.log("IIFE ran");
})();The function executes immediately after definition.
(function(name) {
console.log("Hello " + name);
})("Ava");Pass arguments into the IIFE like a normal function.
An IIFE runs as soon as it is defined.
It is useful for creating a private scope.
IIFEs help avoid polluting the global namespace.
This was especially common before ES modules.
With ES modules, IIFEs are less common but still useful in quick scripts.
They remain a good tool to understand legacy code.
Without
var counter = 0;
// counter is globalWith
(function() {
let counter = 0;
console.log(counter);
})();Wrap the function to make it an expression.
Prefer modules for larger codebases.
Keep IIFEs short and focused.
A function that runs immediately after it is defined.
To create a private scope and avoid globals.
Yes, especially in scripts or legacy code.
Practice: Write an IIFE that logs the sum of two numbers.
// TODO: IIFE that logs 5 + 7
One Possible Solution
(function(a, b) {
console.log(a + b);
})(5, 7);Immediately Invoked Function Expression.
To run code immediately and create a private scope.
Less common with ES modules, but still useful in scripts.
Try passing different values into the IIFE.