0

Here is the code with works perfectly, what is (i) after curly bracket

for (var i = 0; i < 5; i++) {
  setTimeout(function(j) { 
    console.log(j);
  }(i), 1000);
}

Is this the way to pass the parameter value in an anonymous function?

Aramil Rey
  • 3,206
  • 1
  • 18
  • 29
Ali Adravi
  • 19,975
  • 7
  • 75
  • 81

3 Answers3

1

The first argument to setTimeout is a function expression which accepts one argument. i supplies the value to that argument, and (i) calls the function expression with the value of i.

The reason is because you cannot use i directly inside the callback of setTimeout as that will produce unwanted behaviour due to the asynchronous nature of setTimeout and synchronous nature of for loop.

Handling this situation with a function expression ensures that the value of i is bound to j, which correctly produces the desired output.

31piy
  • 22,351
  • 6
  • 45
  • 63
1

That creates the immediately executing function expression () through which the JavaScript engine will directly interpret the function.

Mamun
  • 62,450
  • 9
  • 45
  • 52
1

Lets take this case:

  function fn(j) { // function declaration
    console.log(j);
  }

  fn(j); // function call

That calls the function. Now as functions can also be expressions, they can evaluate to a reference, and one can call that function by adding () after the reference, just as above. That means that

  function(j){ /*..*/ }(i)

actually calls the function directly without waiting.

Jonas Wilms
  • 120,546
  • 16
  • 121
  • 140