0

Look at this code for example:

var arr = [];

var assignFunction = function() {
  for (var i = 0; i < 3; i++) {
    arr[i] = function() {
      console.log(i);
    }

  }
}

arr[0];
arr[1];
arr[2];

You would expect it will assign a function that you can call/run, but its not. I'm looking for good explanation what its really doing. arr[i] is typeof function, meaning it is being assigned, but will never run and print anything to console.

AngularOne
  • 2,760
  • 6
  • 32
  • 46

1 Answers1

0

The "Problem"

You need to call assignFunction to assign the functions to the indices off arr. After that you can execute a function with arr[index]().

why each function prints 3 in the console, you can read in this answer

Working Example

var arr = []

var assignFunction = function() {
  for (var i = 0; i < 3; i++) {
    arr[i] = function() {
      console.log(i)
    }
  }
}

assignFunction()

arr[0]()
arr[1]()
arr[2]()
Roman
  • 4,922
  • 3
  • 22
  • 31