Skip to content

Instantly share code, notes, and snippets.

@richardoey
Last active March 21, 2019 16:56
Show Gist options
  • Save richardoey/5bb2563e7fd9ec55890d9ba25be79ecb to your computer and use it in GitHub Desktop.
Save richardoey/5bb2563e7fd9ec55890d9ba25be79ecb to your computer and use it in GitHub Desktop.
Question 4 (Please explain what is the bug in the following Javascript function, and how to correct it.)
function createArrayOfFunctions(y){
var arr = [];
x = 1
for (let i = 0; i < y ; i++){
arr[i] = function(x){
return x + i;
}
}
return arr;
}
let array = createArrayOfFunctions(5);
console.log(array[1](2));
// I want to revise my work of the previous code
// The bug is because using "var", which is "var" in the for loop.
// It will be correct if we are using the "let" because "var" is for
// global object / variable, and it will turns the above code to return 7
// because it will use the last value of index 'i' in the for loop, which means
// the last value of 'i' is 5 because I call the 'createArrayOfFunctions(5)' and
// it will do an iteration for 5 times.
// 'Let' only works in limited scope block, so the 'i' value will be 1, and the
// correct result should be 3.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment