DEV Community

Discussion on: Closures in JavaScript

Collapse
 
wulymammoth profile image
David • Edited

You're doing great. I always miss a lot of things and love learning about what I've forgotten or don't yet know (there's a lot) :D

When I used to work in JavaScript and interview folks, I typically asked this question that is also solved with the use of a closure:

// what does the following return?
// unfortunately, after a second passes, we get a trail of sixes,
// because the function looks at `i` at invocation time
for (var i = 0; i <= 5; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}

// we can "fix" this by employing an immediately-invoked function expression
// with closure maintaining the state of i at the time of construction
// the following will now print 0, 1, 2, 3, 4, 5
for (var i = 0; i <= 5; i++) {
  (function(i) {
    setTimeout(function() {
      console.log(i);
    }, 1000);
  })(i); 
}
Thread Thread
 
bhagatparwinder profile image
Parwinder 👨🏻‍💻

Haha, I am glad that you have mentioned this example. This is a go-to question for me too.