Skip to content

Instantly share code, notes, and snippets.

@this-is-richard
Last active September 15, 2019 07:06
Show Gist options
  • Save this-is-richard/9b8cc69813c73168e12fc5b740d9caa7 to your computer and use it in GitHub Desktop.
Save this-is-richard/9b8cc69813c73168e12fc5b740d9caa7 to your computer and use it in GitHub Desktop.

Question 3

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 bug above is that "the is" in each function in the array is referencing to "that i" inside the for loop.

Posible Fix: Closures

The function sum now encapsulates/stores a local variable index, and it returns a child function which can then reference index from its parent's scope, rather than that of the for loop.

// Assume y >= 0 and is an integer
function createArrayOfFunctions(y) {
  var arr = [];
  for (var i = 0; i < y; i++) {	
    var sum = function() {
      var index = i
      return function(x) {
        return x + index
      }
    }
    arr[i] = sum()
  }
  return arr;
}

var funcs = createArrayOfFunctions(5)

// Test cases
console.log(funcs[0](7)) // 7
console.log(funcs[1](7)) // 8
console.log(funcs[2](7)) // 9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment