Skip to content

Instantly share code, notes, and snippets.

@kephin
Last active August 15, 2017 15:22
Show Gist options
  • Select an option

  • Save kephin/12218b68b5ccb8cc4e8b06cf461fb58c to your computer and use it in GitHub Desktop.

Select an option

Save kephin/12218b68b5ccb8cc4e8b06cf461fb58c to your computer and use it in GitHub Desktop.
Explain what is the bug in the following JavaScript function, and how to correct it.

Question 4

Please explain what is the bug in the following Javascript function, and how to correct it.

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

Answer:

The problem here is when we are trying to execute the function that was created, the value of 'i' will always be equal as the argument 'y'.

createArrayOfFunctions(3)[0](3) // should be 3 but turn out to be 6
createArrayOfFunctions(3)[1](3) // should be 4 but turn out to be 6
createArrayOfFunctions(3)[2](3) // should be 5 but turn out to be 6

The reason is that the closures of all these three functions are sharing the same lexical environment.The quickest way to solve this problem is to use const / let instead of var, which makes each closure pointing to the block scope variable, i.

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