Home » Posts tagged "closure"

Why does JavaScript loop only use last value?

You see variations of the question, “Why does JavaScript loop only use the last value?” on StackOverflow all the time.  At work, the guy that sits next to me just ran into the same issue.  And the answer to the question requires a solid understanding of closures and variable scope.  Something I’ve written about in the past.  But, when I went back and looked at that article, I was surprised that I had not covered this particular very common topic.

So, here is the basic scenario.  You have some sort of for/next loop that then calls some asynchronous function.  When the function runs, what you see when the code runs is that the last value of the loop index is the value that gets used in the function for every instance that it gets called.

Why does JavaScript loop only use last value?
Photo credit: col_adamson via Visualhunt.com / CC BY

Continue reading “Why does JavaScript loop only use last value?”