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);
}
 
53
Kudos
 
53
Kudos

Now read this

JS to Swift

For my thesis project at Hack Reactor my group elected to build a native iPhone app using Swift. I was excited to learn Swift because I felt that learning another language and developing for a different platform would be a great way to... Continue →