1

I'm learning about js closure from this so post : How do JavaScript closures work?.

I wanted to experiement so I tried creating a loop by creating a function that use callback on the function itself, will doing that I increment an argument and show the result.

At first it didn't worked thent I changed the way I increment my argument and it worked :

function test1(i1){
  console.log("test1 : "+i1.toString());
  setTimeout(function(){test1(i1++);},2500);
}

function test2(i2){
  console.log("test2 : "+i2.toString());
  setTimeout(function(){test2(++i2);},2500);
}

test1(0);
test2(0);

Only changed the i++ to ++i.

The output is the following:

test1 : 0 
test2 : 0 
undefined
test1 : 0 
test2 : 1 
test1 : 0 
test2 : 2 
test1 : 0 
test2 : 3 
test1 : 0 
test2 : 4 
test1 : 0 
test2 : 5

Why does the first step doesn't work?

Edit 2 : I know the diff between i++ and ++i but shouldn't it work anyway?.

Edit: Surely it has something to do with closure ...

m.nachury
  • 972
  • 8
  • 23

1 Answers1

3

in

function test1(i1){
  console.log("test1 : "+i1.toString());
  setTimeout(function(){test1(i1++);},2500);
}

you are always calling test1() with the same value of i1, and then incrementing it.

Since you always call it with the value 0, you get 0 as the output

test1(i1++)

is equivalent to

test1(i1); // it is always getting called with value = 0
i1++; // later being incremented but not used

while in the other function

function test2(i2){
  console.log("test2 : "+i2.toString());
  setTimeout(function(){test2(++i2);},2500);
}

it is equivalent to

i2 = i2 + 1;
test2(i2);
marvel308
  • 10,288
  • 1
  • 21
  • 32
  • Why doesn't it increment the i1 **before** passing it to test1. Is the calculation made once the function is started? Does it pass the calculation and not the result of the calculation? If yes, why does it "execute" the ++i2 (before?) passing it to test2? – m.nachury Sep 07 '17 at 08:50
  • 1
    i1++ means, pass the current value of i1 and then increment in the next step, ++i2 means increment first then pass to the function – marvel308 Sep 07 '17 at 08:51
  • Okay, I would never have guessed ^^. Thanks you! – m.nachury Sep 07 '17 at 08:53
  • 1
    If you debug or add another `console.log` after the `test1(i1++)` you'll see it does get incremented to `1`, it's just that it does this after the function has been executed as has been discussed above! – George Sep 07 '17 at 08:55