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.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops What are Loops?

ZoDo .
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:

counter +=1;

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 .

Brian Pedigo
Brian Pedigo
23,469 Points

You are exactly right that it is due to the scope of the variable. When the var key word is used inside the loop it creates a NEW local variable that is only used inside that loop. Once the loop end so does the newly created variable. However, when the var counter variable is created outside of the loop and only reference inside the loop, it will work as intended and increment the variable by 1 each cycle.

Steven Parker
Steven Parker
210,423 Points

:x: The description of loop-limited scope does not apply in this case — see my answer below.

1 Answer

Steven Parker
Steven Parker
210,423 Points

:point_right: 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).