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 trialQasim Hafeez
12,731 PointsDeclaring message inside for loop
Why can't the message variable be declared inside the for loop? That's how I tried doing it before watching the solution and it didn't work. It would only print out the last object. Can anyone explain why?
1 Answer
Kaitlyn Brown
1,072 PointsI can't see your code since I'm viewing your question through the Community tab instead of on the specific video, but it looks like what you're experiencing is confusion with your variable's scope. When you initialize a variable inside a conditional statement or loop, the variable's scope is limited to that statement. In short, it does not exist outside your loop. However, if you declare the variable outside your loop, it will exist inside the loop. Think of it this way: variables can travel inward, but they cannot travel outward.