Var and let loop scope

Tell us what’s happening:
I’m confused with var loop scope. I think my confusion might have to do with understanding of for loops as well. The code below is from w3schools and is meant to be a simple explanation of var loop scope.
I don’t understand why i can ever be 10. Can someone explain it to me?

 var i = 5;
for (var i = 0; i < 10; i++) {
  // some statements
}
// Here i is 10
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36.

Challenge: Compare Scopes of the var and let Keywords

Link to the challenge:

var creates variables that are function scoped, so both are in the same scope, so first you have var i = 5 and then i becomes 0 with var i = 0
in the loop you have that at each iteration i < 10 is checked - at the end i becomes 10 with one last i++, but i < 10 is false so the loop stops, but i is 10 now

Thank you for the reply.
What I still don’t understand is since we have the condition that i must be less than 10, why is the last i++ allowed, which makes i=10?

the loop doesn’t know that i will be 10, so what happens is that i++ execute, then i < 10 is checked, if it’s true the loop body is run, otherwise the loop stops

Hi , check out the steps mentioned in link below.
for statement

Finally! :bulb:

It’s the sequence of events that I didn’t understand but it makes sense now. The condition is evaluated and if true, the statement block will run. Then the incrementing happens which in this case makes i=10, but when loop runs again, the condition i < 10 is not satisfied and loop stops.
Thank you @G00njan and @ilenia

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.