Predict the output of the following javascript code
for (var i = 0; i < 3; i++) {
const log = () => {
console.log(i)
}
setTimeout(log, 100)
}
Quiz Explanation
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:
The
for
loop initializes a variablei
with a value of0
. It then iterates as long asi
is less than3
, incrementingi
by1
after each iteration.Inside the loop, a
const
arrow functionlog
is defined. This function logs the value ofi
.Then,
setTimeout
is called with thelog
function and a delay of100
milliseconds. Thelog
function is scheduled to execute after100
milliseconds.This process repeats for each iteration of the loop, with
i
taking values0
,1
, and2
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 (after100
milliseconds), the loop has already finished executing. At this point, the value ofi
is3
, as the loop exits wheni
becomes3
. - Since
var
is function-scoped and not block-scoped, the variablei
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
.