0

I have a JavaScript script that I am writing that uses a for loop to assign onclick events to a series of buttons. To fix issues with the scope of i, I am using the following example as the base of my for loops, based upon this answer. I wish I knew the name for this way of creating a for loop, if there even is one.

for (var i = 0; i < 10; i++) (function(i){
    //some code
})(i);

When I run my code through JSLint and JSHint, it gives a warning saying, "Don't make functions within a loop." Referring to the two for loops that are built like above. Questions that I have seen about this warning do not use a loop in the format I am using, so I don't know how they apply to this.

Why is this warning given, and is there a better way than this? Also, is there a name for this for loop format (this last part can be answered in the comments)? If this is related to the other questions, why does this format work?

1 Answers1

2

This is just creating a closure and immediately invoking function expression. The onclick event will happen some time in future, but by that time the loop has finished it's execution & the value of i will be updated to the last value of i<10

So in this case with closure and IIFE the value of i will be bound and will remain in scope.

An alternative way is to use let instead of var

for (let i = 0; i < 10; i++){
  // rest of the code
}

the scope of let is always at block level

brk
  • 48,835
  • 10
  • 56
  • 78