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 trialWilliam Roller
10,775 PointsI 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
Treehouse TeacherThe 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
Treehouse TeacherOr 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
10,801 PointsWhat about other for loop , and cases?
Pavle Lucic
10,801 PointsPavle Lucic
10,801 PointsGood question!