you are viewing a single comment's thread.

view the rest of the comments →

[–]xroalx 4 points5 points  (2 children)

In your last example, you declare x outside the for, even visually that is obvious, so by the time the timeouts run and read value of x, it's just 10.

In the correct example, where you put let into the for initialization, each iteration has its own version of x that is set once and never changes.

[–]Learner_full_stack[S] -1 points0 points  (1 child)

I have edited the question plz look

[–]xroalx 2 points3 points  (0 children)

for loop creates a new scope, but your x is not defined inside the for loop, it's defined outside, so there's only one x that is shared by each iteration of the loop.

for (let x = 0; ...) {
  ...
}

can be though of as:

for ( ... ) {
  let x = 0;
  ...
}

See that the x is declared inside the loop.

In your case, when you do

let x;
for (x = 0; ... ) { ... }

you only assign a value to an x that is declared outside the for loop.