Immediate Invocation
You can define a function and execute it immediately in a single step. This is known by the acronym IIFE (Immediately Invoked Function Expression).
Syntax
To create an IIFE, wrap the entire anonymous function in parentheses (), and then immediately follow it with another pair of parentheses () to invoke it.
(function () {
console.log("This runs immediately!");
})();
They can also accept arguments and return values just like standard functions:
const result = (function (a, b) {
return a + b;
})(1, 2); // Passing 1 and 2 as arguments immediately
console.log(result); // Output: 3
Why Use an IIFE?
While the syntax looks a bit strange, IIFEs are incredibly useful for a few specific architectural reasons:
- Scope Isolation: Because variables declared inside an IIFE (with
letorconst) are scoped only to that function, you can execute complex setup logic without polluting the global scope with temporary variables. - Single Expression Assignment: It is convenient for computing a complex value that requires logic, loops, or conditionals, and assigning the final result directly to a
constvariable. - Async wrappers: In older JavaScript environments that don’t support top-level
await, IIFEs are often used to immediately execute an asynchronous function.
Practical Example
If you need to calculate a configuration total that requires multiple steps, but you want to assign the result to a constant without leaving temporary variables floating around:
// The temporary calculations stay hidden inside the IIFE
const totalCost = (function(messages, bytes) {
const baseCost = messages * bytes;
const tax = baseCost * 0.1;
return baseCost + tax;
})(100, 24);
console.log("Total computed cost:", totalCost);