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.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

do while loop guess variable

why i need to declare the guess variable in global.. can i declare the variable in do while loop like this. is their any problem occured.

do {
   var guess = prompt("Guess the number");
} while {
   ........
}

1 Answer

If you declare a variable in the do portion of a while loop, you may actually end up declaring it multiple times. In a language that uses block level scoping, at the end of the do block, the variable would be deallocated and disappear. However, JavaScript uses function level scoping, so the scope outside the do/while loop is the same as the scope inside it. If the loop runs more than once, it will end up declaring the variable more than once in the same scope. This is ok though, because JavaScript also has variable declaration hoisting, where behind the scenes it actually moves all declarations to the top of the scope.

That said, it is good practice to declare all variables at the top of each function, because in some situations hoisting can lead to some odd side effects.

thnx John Tasto :)