How Javascript closure works inside a loop?

The closures inside loop in Javascript are bit tricky. If the variable binding of the closures are not correct then the unexpected result will come up. Lets consider the following example:

function closureInLoop() {
  for(var i = 0; i < 3 ;i++) {
    setTimeout(function(){
      console.log(i)
    })
  }
}
closureInLoop();
From the above code snippet one might expect that it will show 012 as output but it shows 333 as output.

Output

333


Why is that?

When Javascript executes the closure functions it detects variables those are required for execution and keeps the address of those variables in memory. In the above case the for loop ends asynchronously and the variable i becomes 3 after executing the loop. The method setTimeout has a closure function and it needs the variable i for executing. As Javascript keeps reference of the variable i, it uses that reference value which is 3.

How we can slove this?

Following is the way we can solve this:
function printValue(i){
  setTimeout(function(){
    console.log(i)
  })
}

function closureInLoop() {
  for(var i = 0; i < 3 ;i++) {
    printValue(i);
  }
}
closureInLoop();

Output

012

Comments