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?

I noticed the counter variable has a global scope and is being referenced inside the function. Is that the best practice

Should you set the variable within the function and then update the variable with counter += inside as well?

2 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi William Roller

The while statement doesn't have scope in JavaScript. Other languages have block scope but JavaScript doesn't. So a variable declared inside a while loop is in global scope as well.

Dave McFarland
Dave McFarland
Treehouse Teacher

Or to be more accurate -- a variable declared inside a while loop is in the same scope as the while loop itself. For example, if the while loop is inside a function, then the scope of the while loop is the function. If the while loop isn't inside a function, its scope is the global scope.

Pavle Lucic
Pavle Lucic
10,801 Points

What about other for loop , and cases?