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.

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.