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

Java Java Basics Perfecting the Prototype Censoring Words - Looping Until the Value Passes

Chaz Hall
Chaz Hall
1,970 Points

Declared 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!

Paul Brazell
Paul Brazell
14,371 Points

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

1 Answer

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