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?

2
  • If I can figure out the name of this for loop format, I may be able to better word the Question Title Commented Apr 19, 2018 at 16:50
  • 1
    That's called a closure. Commented Apr 19, 2018 at 17:05

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.