JavaScript Closure

19. July 2016 10:24

 

I’ve heard a lot about closure in JavaScript but until recently didn’t see a good example that made sense to me. In the Pluralsight course Advanced JavaScript by Kyle Simpson I think I finally found it. It starts with a definition:

 

Closure is when a function “remembers” its lexical scope.

 

In this example, the inline function passed to set timeout “remembers” its lexical scope. It always refers to the variable declared outside of its definition. The value at the time the function executes is always 6 (the loop has completed before the first invocation).

 

for(var i = 1; i <= 5;i++) {
    setTimeout(function(){
      console.log("i = " + i);
  }, i*1000);
}

 

So, that led me to wonder how can we get the iterated value logged instead? Instead of an inline function, pass a function to set timeout. Now the value of the variable is passed to the log function and you get the iterated value (1, 2, 3, 4, 5).

 

for(var i = 1; i <= 5;i++) {
      setTimeout(log(i), i*1000);
}

function log(x){
    console.log("x = " + x);
}

 

Here is a fiddle.

About the author

I'm a .NET developer, a husband and a father of three beautiful girls.

Month List