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! While you're at it, check out some resources Treehouse students have shared here.

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

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
26,783 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
231,275 Points

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

1 Answer

Steven Parker
Steven Parker
231,275 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).