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,387
  • 1
  • 19
  • 30
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85

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
  • 23,323
  • 6
  • 47
  • 67
1

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

Mamun
  • 66,969
  • 9
  • 47
  • 59
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
  • 132,000
  • 20
  • 149
  • 151