Solving Loop Closures with IIFEs
You'll learn how to fix the loop variable capture problem using immediately-invoked function expressions—the classic pre-ES6 solution.
The Pre-let Era
Before let existed, all loops used var, which has function scope (not block scope). When closures captured loop variables, they all shared the same variable—leading to the infamous "all callbacks reference the final value" bug you've already encountered.
The IIFE Solution
An immediately-invoked function expression (IIFE) creates a new function scope on each loop iteration. By wrapping your loop body in an IIFE and passing the current loop value as an argument, you "freeze" that value in a fresh scope:
for (var i = 0; i < 3; i++) {
(function(captured) {
setTimeout(function() {
console.log(captured); // 0, 1, 2
}, 100);
})(i); // Pass current i value immediately
}
Why It Works
Think of it like taking a snapshot: each IIFE call creates a new camera (function scope), and captured is a photograph of i at that moment. Even though the original i variable keeps changing, each closure has its own separate captured parameter—a different variable in a different scope.
The pattern: (function(param) { /* closure here */ })(valueToCapture);
Before Modern JavaScript
This technique was the standard way to handle loop closures for years. You'll still see it in older codebases, library code targeting old browsers, or educational material about closures. While let makes this unnecessary today, understanding IIFEs deepens your grasp of how scope and closures interact.
Key Takeaway: IIFEs solve the loop closure problem by creating a new function scope on each iteration, giving each closure its own copy of the loop variable through a function parameter.