G
14

Question about using 'let' inside a for loop in JavaScript

I was building a simple counter in a project last night and used 'let i = 0' inside my for loop. When I tried to console.log(i) after the loop finished, I got a ReferenceError saying 'i is not defined'. I learned that 'let' is block-scoped, so the variable only exists inside the loop's curly braces. Has anyone else run into this and found a clear way to explain it to themselves?
4 comments

Log in to join the discussion

Log In
4 Comments
anthony_fox
Reminds me of when I first learned about closures.
7
roberts.aaron
Just wait until you try to debug a real scope issue. This is basically JavaScript 101.
0
hunt.taylor
Heard that's where the real fun begins.
7
marywells
marywells23d ago
Oh man, debugging scope is the worst. Like when you have a loop and your variable keeps resetting because you used var instead of let. Spent an hour once on a function that kept returning undefined. Turned out I was trying to access a variable outside where it lived. Classic.
4