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

Join the Conversation

1 Comment

  1. Hey There. I discovered your weblog using msn. That is a really neatly written article.
    I will be sure to bookmark it and come back to read more of your
    useful info. Thank you for the post. I will certainly comeback.

Leave a comment

Your email address will not be published. Required fields are marked *