Shaohao
Shaohao

Reputation: 3511

Javascript array with callback function

I tried to have better understanding of JavaScript. Here is a piece of code that I read from JavaScript function closures.

var funcs = [];
// create a bunch of functions
for (var i = 0; i < 3; i++) {
   funcs.push(function() {
    console.log(i);
   })
}
// call them
for (var j = 0; j < 3; j++) {
  funcs[j]();
}

The array funcs has a push callback function. I don't why in the J loop, funcs[j]() will call this function to print the i in the console.
I have tried to understand this sequencey by adding some console messages:

var funcs = [];
console.log("start");
for (var i = 0; i < 3; i++) {
  console.log("i:" + i);
  funcs.push(function(){
    console.log(i);
  })
}

console.log("J loop");
for (var j=0; j<3; j++) {
  console.log("j:" + j);
  funcs[j]();
}

As expected, there is 3 for all three functions.
My question is: How does funcs[j]() calls the funcs.push(...) function? I understant the funcs[j] is reference the j element of the funcs array. But why having parentheses () will call the push(...) function?

Upvotes: 10

Views: 19755

Answers (2)

Arnau Castellv&#237;
Arnau Castellv&#237;

Reputation: 240

First, the 'i' variable are global, and ending the loop, i=3 Then, the functions inside funcs, use the variable "i", then, all functions print "3" in console.

Maybe you wanted to do this:

var funcs = [];
console.log("start");
for (var i = 0; i < 3; i++) {
  console.log("i:" + i);
  funcs.push(function(i){
    console.log(i);
  })
}

console.log("J loop");
for (var j=0; j<3; j++) {
  console.log("j:" + j);
  funcs[j](j);
}

Upvotes: -1

Quentin
Quentin

Reputation: 943142

function() {console.log(i);} is an expression which evaluates to a value that is function that logs i.

funcs.push is a function that adds a value to an array.

Putting () after a function will call that function.

funcs.push(some_value) calls the push function and passes some_value as the value to put in the array.

funcs.push(function() {console.log(i);}) adds the function to the array.

The value of funcs[0] becomes that function.

Putting () after a function will call that function.

funcs[0]() calls the function that is the first value in the array.

Upvotes: 11

Related Questions