Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
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 Parker210,423 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).