Fixing Loop Closures with IIFE
You'll learn how to solve the classic loop closure problem using immediately-invoked function expressions to capture distinct values per iteration.
The Pre-ES6 Solution
Before let existed, JavaScript developers used an immediately-invoked function expression (IIFE) to fix the loop closure trap. An IIFE creates a new function scope on each iteration, capturing the current value of the loop variable rather than sharing a reference to it.
How It Works
When you wrap the loop body in an IIFE, you pass the current loop variable as an argument. Each function call creates a fresh closure with its own copy of that value:
var callbacks = [];
for (var i = 0; i < 3; i++) {
(function(captured) {
callbacks.push(function() {
console.log(captured);
});
})(i);
}
callbacks[0](); // 0
callbacks[1](); // 1
callbacks[2](); // 2
Why This Works
The IIFE executes immediately on each iteration, creating a new lexical environment. The parameter captured holds the current value of i at that moment. When the inner function later accesses captured, it's reading from its own closure—not the shared var i that ended at 3.
Think of it like taking snapshots: instead of everyone pointing to the same live counter, each closure gets its own frozen photo of what the counter showed at that moment.
The Pattern
The typical structure is: (function(param) { /* use param */ })(loopVariable);
The outer parentheses make it an expression, the inner function creates the new scope, and (i) immediately invokes it with the current value.
Key Takeaway: Before let, IIFEs solved the loop closure trap by creating a new function scope per iteration, capturing distinct values instead of sharing a reference to the loop variable.