JavaScript Closures in Loops


Closures is very powerful but also tricky when using in loop.

The reason is that the closure has access to the same variable of its parent. When the code is being excuted, the function closure inside the loop is just being defined but not executed yet. Therefore, the index will always stay the same at the point where the loop has been exited when the function is really being called.

The easiest work around is to define the closure as a function and just assign it to the click event with the index passing in as a param.

You can find more details at
The use of closure in loops