Sobes.tech
Middle

A closure task: why does the function always output 0 instead of the incremented value?

sobes.tech AI

Answer from AI

A common reason why a closure function always outputs 0 instead of the incremented value is the incorrect use of variables in a loop with asynchronous calls or deferred execution.

For example, if a variable is declared inside a loop with var, it has function scope, and all closures will reference the same variable, which at the time of call equals 0.

JavaScript example:

for (var i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i); // always 3, not 0,1,2
  }, 100);
}

To fix this, you should use let, which has block scope, or create an additional closure:

for (let i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i); // 0,1,2
  }, 100);
}

Or with a closure:

for (var i = 0; i < 3; i++) {
  (function(j) {
    setTimeout(function() {
      console.log(j); // 0,1,2
    }, 100);
  })(i);
}

Thus, the problem is that the closure captures the variable, not its value at the moment of function creation.

A closure task: why does the function always output 0… - sobes.tech