Closure and For Loops

Note: If you don’t understand Javascript closures then I recommend you first check out this blog post.

When I was interviewing for a job in San Francisco I was asked to fix the following code:

for (var i = 0; i < 5; i++) {
  setTimeout(function(){
    console.log(i);
  }, 100);
}

If you run the above code the number 5 will be printed to the console five times. The problem here is that the closure scope for each anonymous function at each iteration of the loop points to the same variable. They all point to the same “i”. (In fact, the “i” that the anonymous functions point to has a value that wouldn’t normally be printed if this code functioned as it was intended to. The 5 that is printed is the “i” value that caused the for loop’s condition-expression to evaluate to false.)

By using an IIFE, Immediately Invoked Function Expression, you create a “block scope” of sorts that is unique to each anonymous function. Each anonymous function then points to its own unique “i” variable.

Here’s the solution:

for (i = 0; i < 5; i++) {
  (function(i){
    setTimeout(function(){
      console.log(i)
    }, 100);
  })(i);
}
 
54
Kudos
 
54
Kudos

Now read this

Binary Search Explained

For the uninitiated there are a lot of intimidating buzz words that get thrown around when you listen in on programming discussions. Recursion, hash tables, bitwise operators, and bash commands may seem complicated and mysterious at... Continue →