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 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.

Then you are most likely doing something like this:

//this is what is usually referred to as a global scope if you were to set your variable here let counter =0; your code would //work

for(i=0; i<10;i++){

//this is the scope of the inside of the loop

let counter =0; console.log(This is the counter:${counter});

}

1 Answer

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.