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 trialChaz Hall
1,970 PointsDeclared Variables at beginning of code
This video talks about not declaring variables inside {}. Does this mean that if a variable is declared inside the {} that the rest of the code cannot reference it? If this is true, does that mean that the reason you declare the variable at the beginning of the code is because code inside a {} can pull the variable, but not vice versa? Thanks!
1 Answer
jcorum
71,830 PointsIn this particular case he wants to use the variable (isInvaidWord) both inside and outside the while loop, so it has to be declared outside. There's nothing wrong with declaring variables inside a code block, as long as you don't need to use them outside that block.
Paul Brazell
14,371 PointsExactly
Paul Brazell
14,371 PointsPaul Brazell
14,371 PointsYes. The location where you define your variable determines its scope. If a variable is defined in a function, its scope is limited only to that function and cannot go out of that function. Variables defined outside the {} can be used in other functions.