Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
ZoDo .13,135 Points
Doubts about the counter var.
Hi everyone, doing the challenge I have notice that if you write the counter var inside the while loop with this syntax:
var counter += 1;
it seems not work on the other hand if:
it works perfectly....so why the first syntax is not working considering that counter is in fact a variable? Is it due to the different Scope? Thank to everyone .
Steven Parker228,119 Points
No, this is not a scope issue.
The statement "
var counter += 1;" is not valid because it attempts to create a new variable and increment it before it has been initialized. You can initialize a variable at the same time you declare it, but you cannot increment it at the same time, since it has no initial value.
Scope would not be an issue in any case, because unless it is used inside a function, the keyword var creates variables at global scope. Brian's suggestion that the variable scope would be limited to the loop would only be true if the keyword let was used instead of var (and it still could not be incremented at the same time).