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 trialHabibur Rahman Dipto
8,496 Pointsdo 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
John Tasto
21,587 PointsIf 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.
Habibur Rahman Dipto
8,496 PointsHabibur Rahman Dipto
8,496 Pointsthnx John Tasto :)