Javascript variable scope inside for loop

javascript

Solution

All of your callbacks share the same `i` variable. When the event handler actually runs, `i` is after the end of the array.

You need to wrap the loop body in a self-invoking function that takes `i` as a parameter. This way, each iteration will get its own, unchanging, `i` variable.

For example:

for (var i = 0; i < statesPolyStrings.length; i++) {
    (function(i) {
        ...
    })(i);
}

Problem

How do I maintain access to the `i` variable inside my for loop below? I'm trying to learn, not just get the answer, so a bit of explanation would be very helpful. Thank you! ``` var el, len = statesPolyStrings.length; for (var i = 0; i < len; i++) { el = document.getElementById(statesPolyStrings[i]); google.maps.event.addDomListener(el, 'mouseover', function() { $("#"+statesPolyStrings[i]).addClass("highlight"); statesPolyObjects[i].setOptions({ strokeWeight: '2' }); }); } ```

Original source

Related problems