Skip to content

Instantly share code, notes, and snippets.

@03difoha
Last active September 21, 2019 06:49
Show Gist options
  • Save 03difoha/383c008f47dd57e255c2dffb8e59a7bd to your computer and use it in GitHub Desktop.
Save 03difoha/383c008f47dd57e255c2dffb8e59a7bd to your computer and use it in GitHub Desktop.
function createArrayOfFunctions(y) {
var arr = [];
// fix: for (let i = 0; i < y; i++) {
for (var i = 0; i < y; i++) {
arr[i] = function (x) {
return x + i;
}
// if we run arr[i] immediately inside the loop, we get the desired function.
}
// The problem is that the i inside each generated function all increment with each iteration. (scope leaking)
// so all of the functions here (outside the loop) have the same value of i (the last value)
// instead of each digit between 0 and the input number
return arr;
}
// to fix we can either put the arr variable outside the function and make it global, or a more modern way is
// is to make change var in the for loop into let. this works as let creates a new version of i each loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment