Guest User

Untitled

a guest
Nov 16th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. // So the problem was that we are declaring function inside
  2. // for loop, which has variable i that is global for inner function because it is declared as var.
  3. // So everytime we create a function, the variable i is changed,
  4. // and eveytime the i changes, the funciton is keeping last value.
  5.  
  6. // As a solution we can declare i as let, so that it will be local variable and everytime,
  7. // i changes old value will be kept
  8.  
  9. function createArrayOfFunctions(y) {
  10. var arr = [];
  11. for (let i = 0; i < y; i++) {
  12. arr[i] = function (x) {
  13. return x + i;
  14. }
  15. }
  16. return arr;
  17. }
  18. let a = createArrayOfFunctions(3)
  19. console.log(a[0](1))
  20. console.log(a[1](1))
  21. console.log(a[2](1))
Add Comment
Please, Sign In to add comment