Explore Library
Code QuizAdvanced

Loop Closures With var

A loop uses var to create closures but they all capture the same variable.

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

var hs = makeHandlers();
console.log(hs[0](), hs[1](), hs[2]()); // expected: 0 1 2

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

Watch the code walkthrough

Watch on YouTube →