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 Working with 'for' Loops The for Loop

Wally Mangiliman
Wally Mangiliman
4,041 Points

Are variables declared inside a for loop only defined inside the loop?

If I add console.log(counter) after the for loop, the console says that counter is not defined.

Would help a little bit if you shared your code to fix the error but short answer is yes. Typically a variable declared in a for loop will remain in the loops scope.

1 Answer

Deloris Luckett
Deloris Luckett
6,401 Points

Yes if the variable is only defined in the for loop it is only known inside the loop . If you want it out side the loop you need to define it as a global variable in the function not in the for block.