DEV Community

Discussion on: JavaScript Closure Simply Explained

Collapse
 
jmergenthal profile image
Jurian Mergenthal • Edited

Just a small addition:
instead of

for(var i=0; i<5; i++) {
  setTimeout((function(index) {
    console.log(index)
  })(i), 1000)
}
Enter fullscreen mode Exit fullscreen mode

you can also just use let, instead of var here:

for(let i=0; i<5; i++) {
  setTimeout((function() {
    console.log(i)
  }), 1000)
}
Enter fullscreen mode Exit fullscreen mode

since let variables are bound to the block scope :)