Skip to content

Instantly share code, notes, and snippets.

@mosijava
Created July 27, 2018 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mosijava/3ab545fbe12023700e59171bad20e9c6 to your computer and use it in GitHub Desktop.
Save mosijava/3ab545fbe12023700e59171bad20e9c6 to your computer and use it in GitHub Desktop.
classic JavaScript closure problem
var myFunctions = [];
for (var i = 0; i < 3; i++) { // let's create 3 functions
myFunctions[i] = function() { // and store them in myFunctions
console.log("My value: " + i); // each should log its value.
};
}
for (var j = 0; j < 3; j++) {
myFunctions[j](); // and now let's run each one to see
}
/*output:
My value: 3
My value: 3
My value: 3
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment