Can you help me understand a concept? I'm not inquiring about fixing the code below. I already know that using the let keyword or an iffe can capture the value of i
. What I need clarification on is how the value of i
is accessed in this code snippet. I recently came across a blog post discussing why the following code does not work as expected. You can check out the post here: Blog post
for (var i = 1; i <= 5; i++) {
setTimeout(function() { console.log(i); }, 1000*i); // 6 6 6 6 6
}
The writer argues that the code fails because it passes the variable i
by reference instead of by value. Consequently, when the loop ends and the callbacks are triggered, they all refer to the variable i
which contains the final value of 6. Is this explanation correct?
This leads to my own interpretation. I believe that we aren't actually passing anything to the callback functions of setTimeout
during the loop execution. Instead, we are setting up asynchronous calls. When these closure callback functions eventually run, they access the variable i
based on lexical scoping rules. In essence, the closures look for the variable i
within the scope where the callbacks were created, resulting in the value of 6 since it's evaluated after the for
loop finishes.
So, which explanation holds true - does the function resolve i
to 6 due to passing it as reference each time or is it because of lexical scoping?