How to pass loop variables in a JavaScript callback

This is a common problem encountered i.e. if you are making ajax calls in a loop and you need access to the loop index in the AJAX callback, people often hit the JavaScript ‘reference’ behavior i.e. copying or assigning one variable to another merely makes a reference, not a full copy. This even holds for variables like loop indices, which is extremely counter-intuitive. Anyway, this can be accomplished via JavaScript closures.

1
2
3
4
5
6
7
for (var i = 0; i < arr.length; i++) {
  (function(index) {
    // do your stuff here
    // use the index variable - it is assigned to the value of 'i'
    // that was passed in during the loop iteration.
  })(i);
}

The full answer with more context is present at Stack Overflow