Javascript closures – variable scope question

Its because at the time item.help is evaluated, the loop would have completed in its entirety. Instead, you can do this with a closure:

for (var i = 0; i < helpText.length; i++) {
   document.getElementById(helpText[i].id).onfocus = function(item) {
           return function() {showHelp(item.help);};
         }(helpText[i]);
}

JavaScript doesn’t have block scope but it does have function-scope. By creating a closure, we are capturing the reference to helpText[i] permanently.

Leave a Comment