Sobes.tech
Middle+

What happens to the context when using closures? What will be the context of functions created in a loop with var?

sobes.tech AI

Answer from AI

When using closures, a function "remembers" the context in which it was created, including all variables from the outer scope.

If functions are created in a loop using var, they will all refer to the same variable declared with var outside the function body. As a result, when calling these functions, they will use the current value of this variable, which after the loop ends will be equal to the last value.

Example:

var funcs = [];
for (var i = 0; i < 3; i++) {
  funcs.push(function() { console.log(i); });
}
funcs[0](); // 3
funcs[1](); // 3
funcs[2](); // 3

To achieve the expected behavior, use let (which creates a new variable in each iteration) or create an additional closure:

for (let i = 0; i < 3; i++) {
  funcs.push(function() { console.log(i); });
}
// Now funcs[0]() will output 0, funcs[1]() — 1, funcs[2]() — 2

Or via a closure:

for (var i = 0; i < 3; i++) {
  (function(j) {
    funcs.push(function() { console.log(j); });
  })(i);
}