Explore Library
Code Quiz

Closures Capturing Loop Variables

A loop builds an array of functions but every function returns the same wrong value due to variable scope.

Codejavascript
function makeCounters() {
  const counters = [];
  for (var i = 0; i < 3; i++) {
    counters.push(function () {
      return i;
    });
  }
  return counters;
}

const fns = makeCounters();
console.log(fns[0](), fns[1](), fns[2]());
// expected: 0 1 2

Why does this log "3 3 3" instead of "0 1 2", and how do you fix it?