Closures with Loops
A closure is a function together with the variables it can see from the scope where it was created. The function keeps access to those variables, not copies of their values, so when it runs later it reads whatever they hold at that moment. Inside a loop, that matters for any function that runs after the loop has moved on, such as a timer callback, an event listener or a promise handler.
The problem with var
Section titled “The problem with var”A var declared in a for loop is a single variable shared by every pass. Each timer callback below closes over that one variable, and by the time the timers fire, the loop has finished and i is 3:
const steps = ['preheat', 'mix', 'bake'];
for (var i = 0; i < steps.length; i++) { setTimeout(() => console.log(i, steps[i]), 10 * i);}This prints:
3 undefined3 undefined3 undefinedsteps[3] does not exist, so every callback prints undefined as well.
let creates a new variable for each pass
Section titled “let creates a new variable for each pass”A let declared in the head of a for loop is created afresh for every pass, holding that pass’s value. Each callback closes over its own i:
const steps = ['preheat', 'mix', 'bake'];
for (let i = 0; i < steps.length; i++) { setTimeout(() => console.log(i, steps[i]), 10 * i);}This prints:
0 preheat1 mix2 bakeThis per-pass binding is part of how let is defined in for loops, and it is the main reason to prefer let for loop counters. for...of and for...in loops give each pass a fresh binding as well, whether declared with let or const.
The same difference shows without timers. Each loop below stores functions to call after it has finished:
const withVar = [];for (var i = 1; i <= 3; i++) { withVar.push(() => i * 10);}
const withLet = [];for (let j = 1; j <= 3; j++) { withLet.push(() => j * 10);}
console.log(withVar.map((fn) => fn()));console.log(withLet.map((fn) => fn()));This prints:
[ 40, 40, 40 ][ 10, 20, 30 ]The var loop leaves i at 4, because that is the value that ended the loop, and all three functions read it.
forEach gives each call its own scope
Section titled “forEach gives each call its own scope”forEach() calls its callback once per item, and every call is a separate function call with its own parameters. A closure created inside the callback therefore sees that call’s item and index:
const steps = ['preheat', 'mix', 'bake'];
steps.forEach((step, i) => { setTimeout(() => console.log(i, step), 10 * i);});This prints:
0 preheat1 mix2 bakeFixes for older code that uses var
Section titled “Fixes for older code that uses var”In code that must keep var, the cure is to hand the current value to a function, because a function’s parameters are new variables on every call. setTimeout() passes any arguments after the delay to the callback, and an immediately invoked function expression, or IIFE, does the same job for other kinds of callback:
const steps = ['preheat', 'mix', 'bake'];
for (var i = 0; i < steps.length; i++) { setTimeout((n) => console.log('argument', n, steps[n]), 10 * i, i);}
for (var j = 0; j < steps.length; j++) { (function (n) { setTimeout(() => console.log('IIFE', n, steps[n]), 50 + 10 * n); })(j);}This prints:
argument 0 preheatargument 1 mixargument 2 bakeIIFE 0 preheatIIFE 1 mixIIFE 2 bakeIn both versions, n is a parameter that receives the value of the counter at the moment of the call, so later changes to the counter do not reach it. In new code, use let and none of this is needed. IIFE and Variable scope cover the background.
Steve Griffith covers this topic in his video JavaScript Closures with Loops.