Doubt from for loops and functions

Can someone explain me how do we get output as 5,5,5,5,5 when range of “i” is set to <5 ?

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

1 Like

@cryptowriter.eth

In this code, a for loop is used to iterate from 0 to 4 because the condition in the for loop is set to i < 5. During each iteration of the loop, a setTimeout function is called which schedules a function execution after a delay of 1000 milliseconds (i.e. 1 second).

Now, the important thing to understand here is that the setTimeout function does not block the execution of the loop. Instead, the loop completes its iterations and sets i to 5.

Then, after the loop has completed, the scheduled function executions begin, which will execute after a delay of 1000 milliseconds. When these functions execute, they will all reference the same i variable in memory, which at this point is 5. As a result, when console.log(i) is called inside these functions, they will all output 5, because that is the value of i that they are referencing.

So the final output will be 5, 5, 5, 5, 5, because each function execution outputs the value of i, which is 5 at the time of execution.

1 Like

But how does the function sets i to 5 ?

@cryptowriter.eth
The function does not set i to 5 directly.

The reason why i is logged as 5 when the code is run is because of how the setTimeout method works in JavaScript.

When the setTimeout method is called, it creates a timer that will execute the function passed as its first argument after a specified time interval (in this case, 1000 milliseconds or 1 second).

So in the code you provided, the loop runs 5 times, and each time it calls setTimeout, it schedules the execution of the inner function (which logs the value of i) after a delay of 1 second.

After the loop completes, the value of i will be 5, and when the scheduled functions finally execute, they will each log the value of i, which is 5 in all cases.

Therefore, the output will be 5 printed 5 times, with a 1 second delay between each print statement.

1 Like

okay! got it. thank you so much.

1 Like