I have previously posted on SO:
How would you set the following loop to log like below?
The answer was to change var
to let
.
I am currently learning javascript after having studied python for a few months. I just wanted to see where my analysis is going wrong as I am struggling to apply the concept of block scope and function scope here.
Here is the original code snippet:
for (var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, i * 1000 );
}
What I do not understand is, if I delete the setTimeout function bit and end up with this:
for (var i = 0; i < 5; i++) {
console.log(i);
}
The output changes from
5
5
5
5
5
to
0
1
2
3
4
which was what I thought it should initially do. I don't understand why in the first case the need to use let i
was necessary but in the second case it works fine with var
.
Another point of confusion is that, if you take the first code snippet, with the setTimeout
function, the value of the final i
printed is 5. This does not make sense considering our initial for loop was only supposed to run till i<5
.
The last point I am struggling with is that even if i
was allowed to take on the value of 5, it seems the action (printing i) is done after the loop? I am saying this because i
starts off at 0, and increases in value iteratively, here we are printing the final value of i
5 times. This must mean the computer has gone through the iteration before and then decides to do the action using the final value of i
but 5 times?
Essentially I thought it goes as follows, we create a variable i
using var
, we say that as long as i
is less than 5, do something, after doing something increase i
by 1 and repeat.
Instead what it looks like from the first codes output is, create a variable i
using var
, i
increases by 1 till i
equals 5, do the action as many times as the number of iterations.
Sorry if this question is not coherent but I can't seem to apply the concepts of function scope and block scope here, which I feel is the key issue. Can someone please elaborate on this particular example?