Skip to content

Instantly share code, notes, and snippets.

@mattpat
Created October 2, 2011 21:36
Show Gist options
  • Save mattpat/1257994 to your computer and use it in GitHub Desktop.
Save mattpat/1257994 to your computer and use it in GitHub Desktop.
How to avoid accidental closures in loops.
function makeAlerter(x){
return function(e){
alert(x);
};
}
for (var i = 0; i < 10; i++)
elements[i].addEventListener('click', makeAlerter(i));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment