DEV Community

Think1s
Think1s

Posted on

JS Interview Question #4

Read more articles in Think1s

What will be the output of the following code?

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


The output of the code will be:
5
5
5
5
5

Explanation:

For each iteration, a setTimeout method is called, which takes a callback function that logs the current value of i to the console.

However, since setTimeout is an asynchronous function, it does not execute immediately. Instead, it schedules the callback function to execute after a certain amount of time. In this case, the amount of time is set to 0, which means the callback function is scheduled to execute as soon as possible, but not immediately.

Therefore, when the for loop finishes executing, the value of i will be 5. This means that all five setTimeout functions will execute their callback function with i equal to 5, resulting in the output of 5 printed five times to the console.

Read more articles in Think1s

Top comments (0)