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?

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?