Immediately Invoked Function Expressions (IIFE)
You'll learn how to create and execute a function in one line, creating a private scope instantly.
What Is an IIFE?
An IIFE (pronounced "iffy") is a function expression that runs immediately after you define it. Instead of declaring a function and calling it later, you wrap it in parentheses and invoke it right away. This creates a temporary, isolated scope that executes once and disappears.
Think of it like a popup tent: you set it up, use it for privacy, then pack it away. What happens inside stays inside.
The IIFE Pattern
The basic syntax looks like this:
(function() {
// Code here runs immediately
// Variables here are private
})();
The outer parentheses turn the function declaration into an expression, and the final () invokes it immediately.
Why Use an IIFE?
Isolation: Variables inside an IIFE don't leak into the outer scope:
(function() {
var secret = "hidden";
})();
// secret doesn't exist out here
No pollution: Before modern features, IIFEs were the primary way to avoid cluttering the global scope with temporary variables.
var result = (function() {
var temp = 5 + 10;
return temp * 2;
})();
// result is 30, but temp is gone
You can also pass arguments to an IIFE just like any function call.
Key Takeaway: IIFEs create an isolated scope that executes immediately and then vanishes, keeping temporary variables from polluting outer scopes—a classic pattern for creating privacy in JavaScript.