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?