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?
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?
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.
That creates the immediately executing function expression () through which the JavaScript engine will directly interpret the function.
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.