0

Can someone explain me why var doesn't overwrite previous values inside for loop. I know that var overwrite values when is in function and then I should use let or anonymous function. Below is an simple example:

for (var a=0; a<10; a++) {
  console.log(a);
}

Output is from 0-9. But since var has function scope, in my reasoning the variable should be overwritten and output 9 times the same number(9).

0

1 Answer 1

0

I think I understand your question.

So, your first example. Output cannot be overwritten. It's output. Part of the name is you put it out. So it's 0, put the 0 out. Now it's 1, put the 1 out. Now it's 2, put the 2 out. And so on.

In your second example, there's a time out. So those functions don't execute until the for loop is finished. Once the for loop is finished, a = 10. Output 10. a is still 10. Output 10 again.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.