Predict the output of the following javascript code

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

 

 

 

 

In this code, a for loop is used to create three instances of a setTimeout function. Each instance logs the value of i after a delay of 100 milliseconds. Let's break down what happens:

  1. The for loop initializes a variable i with a value of 0. It then iterates as long as i is less than 3, incrementing i by 1 after each iteration.

  2. Inside the loop, a const arrow function log is defined. This function logs the value of i.

  3. Then, setTimeout is called with the log function and a delay of 100 milliseconds. The log function is scheduled to execute after 100 milliseconds.

  4. This process repeats for each iteration of the loop, with i taking values 0, 1, and 2 successively.

However, there's a catch due to the closure and the behavior of var declaration:

  • The setTimeout function is asynchronous, meaning it doesn't execute immediately but rather after a certain delay (in this case, 100 milliseconds).
  • By the time the log function executes (after 100 milliseconds), the loop has already finished executing. At this point, the value of i is 3, as the loop exits when i becomes 3.
  • Since var is function-scoped and not block-scoped, the variable i is scoped to the function containing the loop, not the individual iterations of the loop.

So, when the log function executes, it references the same variable i in its outer scope, which is 3 at that point.

As a result, when each log function executes, it logs the final value of i, which is 3, regardless of the iteration:

3
3
3

All three instances of the log function print 3, because by the time they execute, the loop has finished and i is 3.