Skip to content

Instantly share code, notes, and snippets.

@elvismetaphor
Last active June 5, 2018 09:40
Show Gist options
  • Save elvismetaphor/a2c2140b0ec6634400676a0807c70b17 to your computer and use it in GitHub Desktop.
Save elvismetaphor/a2c2140b0ec6634400676a0807c70b17 to your computer and use it in GitHub Desktop.

Sympton

For this code

function createArrayOfFunctions(y) {
  var arr = [];
  for(var i = 0; i<y; i++) {
    arr[i] = function(x) { return x + i; }
  }
  return arr; 
}

if you use the function

var funs = createArrayOfFunctions(5);
for (var index = 0; index < 5; i++) {
    console.log(funs[index](0));
}

You will get the result

5
5
5
5
5

Because the i in { return x + i} is declared ouside the closure, and all functions uses the same i variable, each function will return the same value if all inputs are the same.

Solution

Assign i into a local variable and put the local variable into the function

function createArrayOfFunctions(y) {
  var arr = [];
  for(var i = 0; i<y; i++) {
    let local = i;
    arr[i] = function(x) { return x + local; }
  }
  return arr; 
}

Another solution

Use another function to create the functions which are stored in the arr

function makeFunction(i) {
  return function(x) {
    return x + i;
  }
}

function createArrayOfFunctions(y) {
  var arr = [];
  for (var i = 0; i < y; i++) {
    arr[i] = makeFunction(i);
  }
  return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment